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

lightningnetwork / lnd / 17381199536

01 Sep 2025 02:59PM UTC coverage: 66.638% (-0.02%) from 66.658%
17381199536

Pull #10182

github

web-flow
Merge e24e285e3 into 84b2c20ea
Pull Request #10182: Aux feature bits

52 of 119 new or added lines in 6 files covered. (43.7%)

86 existing lines in 20 files now uncovered.

136005 of 204094 relevant lines covered (66.64%)

21453.0 hits per line

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

76.47
/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/routing/route"
35
        "github.com/lightningnetwork/lnd/ticker"
36
        "github.com/lightningnetwork/lnd/tlv"
37
)
38

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

301
        // AuxChannelNegotiator is an optional interface that allows aux
302
        // channel implementations to inject and process feature bits during
303
        // init and channel_reestablish messages.
304
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
305

306
        // QuiescenceTimeout is the max duration that the channel can be
307
        // quiesced. Any dependent protocols (dynamic commitments, splicing,
308
        // etc.) must finish their operations under this timeout value,
309
        // otherwise the node will disconnect.
310
        QuiescenceTimeout time.Duration
311
}
312

313
// channelLink is the service which drives a channel's commitment update
314
// state-machine. In the event that an HTLC needs to be propagated to another
315
// link, the forward handler from config is used which sends HTLC to the
316
// switch. Additionally, the link encapsulate logic of commitment protocol
317
// message ordering and updates.
318
type channelLink struct {
319
        // The following fields are only meant to be used *atomically*
320
        started       int32
321
        reestablished int32
322
        shutdown      int32
323

324
        // failed should be set to true in case a link error happens, making
325
        // sure we don't process any more updates.
326
        failed bool
327

328
        // keystoneBatch represents a volatile list of keystones that must be
329
        // written before attempting to sign the next commitment txn. These
330
        // represent all the HTLC's forwarded to the link from the switch. Once
331
        // we lock them into our outgoing commitment, then the circuit has a
332
        // keystone, and is fully opened.
333
        keystoneBatch []Keystone
334

335
        // openedCircuits is the set of all payment circuits that will be open
336
        // once we make our next commitment. After making the commitment we'll
337
        // ACK all these from our mailbox to ensure that they don't get
338
        // re-delivered if we reconnect.
339
        openedCircuits []CircuitKey
340

341
        // closedCircuits is the set of all payment circuits that will be
342
        // closed once we make our next commitment. After taking the commitment
343
        // we'll ACK all these to ensure that they don't get re-delivered if we
344
        // reconnect.
345
        closedCircuits []CircuitKey
346

347
        // channel is a lightning network channel to which we apply htlc
348
        // updates.
349
        channel *lnwallet.LightningChannel
350

351
        // cfg is a structure which carries all dependable fields/handlers
352
        // which may affect behaviour of the service.
353
        cfg ChannelLinkConfig
354

355
        // mailBox is the main interface between the outside world and the
356
        // link. All incoming messages will be sent over this mailBox. Messages
357
        // include new updates from our connected peer, and new packets to be
358
        // forwarded sent by the switch.
359
        mailBox MailBox
360

361
        // upstream is a channel that new messages sent from the remote peer to
362
        // the local peer will be sent across.
363
        upstream chan lnwire.Message
364

365
        // downstream is a channel in which new multi-hop HTLC's to be
366
        // forwarded will be sent across. Messages from this channel are sent
367
        // by the HTLC switch.
368
        downstream chan *htlcPacket
369

370
        // updateFeeTimer is the timer responsible for updating the link's
371
        // commitment fee every time it fires.
372
        updateFeeTimer *time.Timer
373

374
        // uncommittedPreimages stores a list of all preimages that have been
375
        // learned since receiving the last CommitSig from the remote peer. The
376
        // batch will be flushed just before accepting the subsequent CommitSig
377
        // or on shutdown to avoid doing a write for each preimage received.
378
        uncommittedPreimages []lntypes.Preimage
379

380
        sync.RWMutex
381

382
        // hodlQueue is used to receive exit hop htlc resolutions from invoice
383
        // registry.
384
        hodlQueue *queue.ConcurrentQueue
385

386
        // hodlMap stores related htlc data for a circuit key. It allows
387
        // resolving those htlcs when we receive a message on hodlQueue.
388
        hodlMap map[models.CircuitKey]hodlHtlc
389

390
        // log is a link-specific logging instance.
391
        log btclog.Logger
392

393
        // isOutgoingAddBlocked tracks whether the channelLink can send an
394
        // UpdateAddHTLC.
395
        isOutgoingAddBlocked atomic.Bool
396

397
        // isIncomingAddBlocked tracks whether the channelLink can receive an
398
        // UpdateAddHTLC.
399
        isIncomingAddBlocked atomic.Bool
400

401
        // flushHooks is a hookMap that is triggered when we reach a channel
402
        // state with no live HTLCs.
403
        flushHooks hookMap
404

405
        // outgoingCommitHooks is a hookMap that is triggered after we send our
406
        // next CommitSig.
407
        outgoingCommitHooks hookMap
408

409
        // incomingCommitHooks is a hookMap that is triggered after we receive
410
        // our next CommitSig.
411
        incomingCommitHooks hookMap
412

413
        // quiescer is the state machine that tracks where this channel is with
414
        // respect to the quiescence protocol.
415
        quiescer Quiescer
416

417
        // quiescenceReqs is a queue of requests to quiesce this link. The
418
        // members of the queue are send-only channels we should call back with
419
        // the result.
420
        quiescenceReqs chan StfuReq
421

422
        // cg is a helper that encapsulates a wait group and quit channel and
423
        // allows contexts that either block or cancel on those depending on
424
        // the use case.
425
        cg *fn.ContextGuard
426
}
427

428
// hookMap is a data structure that is used to track the hooks that need to be
429
// called in various parts of the channelLink's lifecycle.
430
//
431
// WARNING: NOT thread-safe.
432
type hookMap struct {
433
        // allocIdx keeps track of the next id we haven't yet allocated.
434
        allocIdx atomic.Uint64
435

436
        // transient is a map of hooks that are only called the next time invoke
437
        // is called. These hooks are deleted during invoke.
438
        transient map[uint64]func()
439

440
        // newTransients is a channel that we use to accept new hooks into the
441
        // hookMap.
442
        newTransients chan func()
443
}
444

445
// newHookMap initializes a new empty hookMap.
446
func newHookMap() hookMap {
648✔
447
        return hookMap{
648✔
448
                allocIdx:      atomic.Uint64{},
648✔
449
                transient:     make(map[uint64]func()),
648✔
450
                newTransients: make(chan func()),
648✔
451
        }
648✔
452
}
648✔
453

454
// alloc allocates space in the hook map for the supplied hook, the second
455
// argument determines whether it goes into the transient or persistent part
456
// of the hookMap.
457
func (m *hookMap) alloc(hook func()) uint64 {
5✔
458
        // We assume we never overflow a uint64. Seems OK.
5✔
459
        hookID := m.allocIdx.Add(1)
5✔
460
        if hookID == 0 {
5✔
461
                panic("hookMap allocIdx overflow")
×
462
        }
463
        m.transient[hookID] = hook
5✔
464

5✔
465
        return hookID
5✔
466
}
467

468
// invoke is used on a hook map to call all the registered hooks and then clear
469
// out the transient hooks so they are not called again.
470
func (m *hookMap) invoke() {
2,752✔
471
        for _, hook := range m.transient {
2,757✔
472
                hook()
5✔
473
        }
5✔
474

475
        m.transient = make(map[uint64]func())
2,752✔
476
}
477

478
// hodlHtlc contains htlc data that is required for resolution.
479
type hodlHtlc struct {
480
        add        lnwire.UpdateAddHTLC
481
        sourceRef  channeldb.AddRef
482
        obfuscator hop.ErrorEncrypter
483
}
484

485
// NewChannelLink creates a new instance of a ChannelLink given a configuration
486
// and active channel that will be used to verify/apply updates to.
487
func NewChannelLink(cfg ChannelLinkConfig,
488
        channel *lnwallet.LightningChannel) ChannelLink {
218✔
489

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

218✔
492
        // If the max fee exposure isn't set, use the default.
218✔
493
        if cfg.MaxFeeExposure == 0 {
433✔
494
                cfg.MaxFeeExposure = DefaultMaxFeeExposure
215✔
495
        }
215✔
496

497
        var qsm Quiescer
218✔
498
        if !cfg.DisallowQuiescence {
436✔
499
                qsm = NewQuiescer(QuiescerCfg{
218✔
500
                        chanID: lnwire.NewChanIDFromOutPoint(
218✔
501
                                channel.ChannelPoint(),
218✔
502
                        ),
218✔
503
                        channelInitiator: channel.Initiator(),
218✔
504
                        sendMsg: func(s lnwire.Stfu) error {
223✔
505
                                return cfg.Peer.SendMessage(false, &s)
5✔
506
                        },
5✔
507
                        timeoutDuration: cfg.QuiescenceTimeout,
508
                        onTimeout: func() {
5✔
509
                                cfg.Peer.Disconnect(ErrQuiescenceTimeout)
5✔
510
                        },
5✔
511
                })
512
        } else {
×
513
                qsm = &quiescerNoop{}
×
514
        }
×
515

516
        quiescenceReqs := make(
218✔
517
                chan fn.Req[fn.Unit, fn.Result[lntypes.ChannelParty]], 1,
218✔
518
        )
218✔
519

218✔
520
        return &channelLink{
218✔
521
                cfg:                 cfg,
218✔
522
                channel:             channel,
218✔
523
                hodlMap:             make(map[models.CircuitKey]hodlHtlc),
218✔
524
                hodlQueue:           queue.NewConcurrentQueue(10),
218✔
525
                log:                 log.WithPrefix(logPrefix),
218✔
526
                flushHooks:          newHookMap(),
218✔
527
                outgoingCommitHooks: newHookMap(),
218✔
528
                incomingCommitHooks: newHookMap(),
218✔
529
                quiescer:            qsm,
218✔
530
                quiescenceReqs:      quiescenceReqs,
218✔
531
                cg:                  fn.NewContextGuard(),
218✔
532
        }
218✔
533
}
534

535
// A compile time check to ensure channelLink implements the ChannelLink
536
// interface.
537
var _ ChannelLink = (*channelLink)(nil)
538

539
// Start starts all helper goroutines required for the operation of the channel
540
// link.
541
//
542
// NOTE: Part of the ChannelLink interface.
543
func (l *channelLink) Start() error {
216✔
544
        if !atomic.CompareAndSwapInt32(&l.started, 0, 1) {
216✔
545
                err := fmt.Errorf("channel link(%v): already started", l)
×
546
                l.log.Warn("already started")
×
547
                return err
×
548
        }
×
549

550
        l.log.Info("starting")
216✔
551

216✔
552
        // If the config supplied watchtower client, ensure the channel is
216✔
553
        // registered before trying to use it during operation.
216✔
554
        if l.cfg.TowerClient != nil {
219✔
555
                err := l.cfg.TowerClient.RegisterChannel(
3✔
556
                        l.ChanID(), l.channel.State().ChanType,
3✔
557
                )
3✔
558
                if err != nil {
3✔
559
                        return err
×
560
                }
×
561
        }
562

563
        l.mailBox.ResetMessages()
216✔
564
        l.hodlQueue.Start()
216✔
565

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

580
                // NOTE: This is automatically done by the switch when it
581
                // starts up, but is necessary to prevent inconsistencies in
582
                // the case that the link flaps. This is a result of a link's
583
                // life-cycle being shorter than that of the switch.
584
                chanID := l.ShortChanID()
216✔
585
                err = l.cfg.Circuits.TrimOpenCircuits(chanID, localHtlcIndex)
216✔
586
                if err != nil {
216✔
587
                        return fmt.Errorf("unable to trim circuits above "+
×
588
                                "local htlc index %d: %v", localHtlcIndex, err)
×
589
                }
×
590

591
                // Since the link is live, before we start the link we'll update
592
                // the ChainArbitrator with the set of new channel signals for
593
                // this channel.
594
                //
595
                // TODO(roasbeef): split goroutines within channel arb to avoid
596
                go func() {
432✔
597
                        signals := &contractcourt.ContractSignals{
216✔
598
                                ShortChanID: l.channel.ShortChanID(),
216✔
599
                        }
216✔
600

216✔
601
                        err := l.cfg.UpdateContractSignals(signals)
216✔
602
                        if err != nil {
216✔
603
                                l.log.Errorf("unable to update signals")
×
604
                        }
×
605
                }()
606
        }
607

608
        l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
216✔
609

216✔
610
        l.cg.WgAdd(1)
216✔
611
        go l.htlcManager(context.TODO())
216✔
612

216✔
613
        return nil
216✔
614
}
615

616
// Stop gracefully stops all active helper goroutines, then waits until they've
617
// exited.
618
//
619
// NOTE: Part of the ChannelLink interface.
620
func (l *channelLink) Stop() {
217✔
621
        if !atomic.CompareAndSwapInt32(&l.shutdown, 0, 1) {
229✔
622
                l.log.Warn("already stopped")
12✔
623
                return
12✔
624
        }
12✔
625

626
        l.log.Info("stopping")
205✔
627

205✔
628
        // As the link is stopping, we are no longer interested in htlc
205✔
629
        // resolutions coming from the invoice registry.
205✔
630
        l.cfg.Registry.HodlUnsubscribeAll(l.hodlQueue.ChanIn())
205✔
631

205✔
632
        if l.cfg.ChainEvents.Cancel != nil {
208✔
633
                l.cfg.ChainEvents.Cancel()
3✔
634
        }
3✔
635

636
        // Ensure the channel for the timer is drained.
637
        if l.updateFeeTimer != nil {
410✔
638
                if !l.updateFeeTimer.Stop() {
205✔
639
                        select {
×
640
                        case <-l.updateFeeTimer.C:
×
641
                        default:
×
642
                        }
643
                }
644
        }
645

646
        if l.hodlQueue != nil {
410✔
647
                l.hodlQueue.Stop()
205✔
648
        }
205✔
649

650
        l.cg.Quit()
205✔
651
        l.cg.WgWait()
205✔
652

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

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

673
// WaitForShutdown blocks until the link finishes shutting down, which includes
674
// termination of all dependent goroutines.
675
func (l *channelLink) WaitForShutdown() {
×
676
        l.cg.WgWait()
×
677
}
×
678

679
// EligibleToForward returns a bool indicating if the channel is able to
680
// actively accept requests to forward HTLC's. We're able to forward HTLC's if
681
// we are eligible to update AND the channel isn't currently flushing the
682
// outgoing half of the channel.
683
//
684
// NOTE: MUST NOT be called from the main event loop.
685
func (l *channelLink) EligibleToForward() bool {
616✔
686
        l.RLock()
616✔
687
        defer l.RUnlock()
616✔
688

616✔
689
        return l.eligibleToForward()
616✔
690
}
616✔
691

692
// eligibleToForward returns a bool indicating if the channel is able to
693
// actively accept requests to forward HTLC's. We're able to forward HTLC's if
694
// we are eligible to update AND the channel isn't currently flushing the
695
// outgoing half of the channel.
696
//
697
// NOTE: MUST be called from the main event loop.
698
func (l *channelLink) eligibleToForward() bool {
616✔
699
        return l.eligibleToUpdate() && !l.IsFlushing(Outgoing)
616✔
700
}
616✔
701

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

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

724
        return l.isIncomingAddBlocked.Swap(false)
5✔
725
}
726

727
// DisableAdds sets the ChannelUpdateHandler state to allow UpdateAddHtlc's in
728
// the specified direction. It returns true if the state was changed and false
729
// if the desired state was already set before the method was called.
730
func (l *channelLink) DisableAdds(linkDirection LinkDirection) bool {
17✔
731
        if linkDirection == Outgoing {
25✔
732
                return !l.isOutgoingAddBlocked.Swap(true)
8✔
733
        }
8✔
734

735
        return !l.isIncomingAddBlocked.Swap(true)
12✔
736
}
737

738
// IsFlushing returns true when UpdateAddHtlc's are disabled in the direction of
739
// the argument.
740
func (l *channelLink) IsFlushing(linkDirection LinkDirection) bool {
1,594✔
741
        if linkDirection == Outgoing {
2,714✔
742
                return l.isOutgoingAddBlocked.Load()
1,120✔
743
        }
1,120✔
744

745
        return l.isIncomingAddBlocked.Load()
477✔
746
}
747

748
// OnFlushedOnce adds a hook that will be called the next time the channel
749
// state reaches zero htlcs. This hook will only ever be called once. If the
750
// channel state already has zero htlcs, then this will be called immediately.
751
func (l *channelLink) OnFlushedOnce(hook func()) {
4✔
752
        select {
4✔
753
        case l.flushHooks.newTransients <- hook:
4✔
754
        case <-l.cg.Done():
×
755
        }
756
}
757

758
// OnCommitOnce adds a hook that will be called the next time a CommitSig
759
// message is sent in the argument's LinkDirection. This hook will only ever be
760
// called once. If no CommitSig is owed in the argument's LinkDirection, then
761
// we will call this hook be run immediately.
762
func (l *channelLink) OnCommitOnce(direction LinkDirection, hook func()) {
4✔
763
        var queue chan func()
4✔
764

4✔
765
        if direction == Outgoing {
8✔
766
                queue = l.outgoingCommitHooks.newTransients
4✔
767
        } else {
4✔
768
                queue = l.incomingCommitHooks.newTransients
×
769
        }
×
770

771
        select {
4✔
772
        case queue <- hook:
4✔
773
        case <-l.cg.Done():
×
774
        }
775
}
776

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

4✔
789
        select {
4✔
790
        case l.quiescenceReqs <- req:
4✔
791
        case <-l.cg.Done():
×
792
                req.Resolve(fn.Err[lntypes.ChannelParty](ErrLinkShuttingDown))
×
793
        }
794

795
        return out
4✔
796
}
797

798
// isReestablished returns true if the link has successfully completed the
799
// channel reestablishment dance.
800
func (l *channelLink) isReestablished() bool {
619✔
801
        return atomic.LoadInt32(&l.reestablished) == 1
619✔
802
}
619✔
803

804
// markReestablished signals that the remote peer has successfully exchanged
805
// channel reestablish messages and that the channel is ready to process
806
// subsequent messages.
807
func (l *channelLink) markReestablished() {
216✔
808
        atomic.StoreInt32(&l.reestablished, 1)
216✔
809
}
216✔
810

811
// IsUnadvertised returns true if the underlying channel is unadvertised.
812
func (l *channelLink) IsUnadvertised() bool {
5✔
813
        state := l.channel.State()
5✔
814
        return state.ChannelFlags&lnwire.FFAnnounceChannel == 0
5✔
815
}
5✔
816

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

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

4✔
832
        return feePerKw, nil
4✔
833
}
834

835
// shouldAdjustCommitFee returns true if we should update our commitment fee to
836
// match that of the network fee. We'll only update our commitment fee if the
837
// network fee is +/- 10% to our commitment fee or if our current commitment
838
// fee is below the minimum relay fee.
839
func shouldAdjustCommitFee(netFee, chanFee,
840
        minRelayFee chainfee.SatPerKWeight) bool {
14✔
841

14✔
842
        switch {
14✔
843
        // If the network fee is greater than our current commitment fee and
844
        // our current commitment fee is below the minimum relay fee then
845
        // we should switch to it no matter if it is less than a 10% increase.
846
        case netFee > chanFee && chanFee < minRelayFee:
1✔
847
                return true
1✔
848

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

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

859
        // Otherwise, we won't modify our fee.
860
        default:
7✔
861
                return false
7✔
862
        }
863
}
864

865
// failCb is used to cut down on the argument verbosity.
866
type failCb func(update *lnwire.ChannelUpdate1) lnwire.FailureMessage
867

868
// createFailureWithUpdate creates a ChannelUpdate when failing an incoming or
869
// outgoing HTLC. It may return a FailureMessage that references a channel's
870
// alias. If the channel does not have an alias, then the regular channel
871
// update from disk will be returned.
872
func (l *channelLink) createFailureWithUpdate(incoming bool,
873
        outgoingScid lnwire.ShortChannelID, cb failCb) lnwire.FailureMessage {
25✔
874

25✔
875
        // Determine which SCID to use in case we need to use aliases in the
25✔
876
        // ChannelUpdate.
25✔
877
        scid := outgoingScid
25✔
878
        if incoming {
25✔
879
                scid = l.ShortChanID()
×
880
        }
×
881

882
        // Try using the FailAliasUpdate function. If it returns nil, fallback
883
        // to the non-alias behavior.
884
        update := l.cfg.FailAliasUpdate(scid, incoming)
25✔
885
        if update == nil {
44✔
886
                // Fallback to the non-alias behavior.
19✔
887
                var err error
19✔
888
                update, err = l.cfg.FetchLastChannelUpdate(l.ShortChanID())
19✔
889
                if err != nil {
19✔
890
                        return &lnwire.FailTemporaryNodeFailure{}
×
891
                }
×
892
        }
893

894
        return cb(update)
25✔
895
}
896

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

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

173✔
906
        // First, we'll generate our ChanSync message to send to the other
173✔
907
        // side. Based on this message, the remote party will decide if they
173✔
908
        // need to retransmit any data or not.
173✔
909
        localChanSyncMsg, err := chanState.ChanSyncMsg()
173✔
910
        if err != nil {
173✔
911
                return fmt.Errorf("unable to generate chan sync message for "+
×
912
                        "ChannelPoint(%v)", l.channel.ChannelPoint())
×
913
        }
×
914

915
        // If we have an AuxChannelNegotiator, get custom feature bits to
916
        // include in the channel reestablish message.
917
        l.cfg.AuxChannelNegotiator.WhenSome(
173✔
918
                func(negotiator lnwallet.AuxChannelNegotiator) {
173✔
NEW
919
                        fundingPoint := l.channel.ChannelPoint()
×
NEW
920
                        auxBlob := l.FundingCustomBlob()
×
NEW
921

×
NEW
922
                        auxFeatures, err := negotiator.GetReestablishFeatures(
×
NEW
923
                                lnwire.NewChanIDFromOutPoint(fundingPoint),
×
NEW
924
                                auxBlob.UnwrapOr(nil),
×
NEW
925
                        )
×
NEW
926
                        if err != nil {
×
NEW
927
                                l.log.Warnf("Failed to get aux reestablish "+
×
NEW
928
                                        "features: %v", err)
×
NEW
929

×
NEW
930
                                return
×
NEW
931
                        }
×
932

NEW
933
                        localChanSyncMsg.AuxFeatures = fn.Some(auxFeatures)
×
934
                },
935
        )
936

937
        if err := l.cfg.Peer.SendMessage(true, localChanSyncMsg); err != nil {
173✔
938
                return fmt.Errorf("unable to send chan sync message for "+
×
939
                        "ChannelPoint(%v): %v", l.channel.ChannelPoint(), err)
×
940
        }
×
941

942
        var msgsToReSend []lnwire.Message
173✔
943

173✔
944
        // Next, we'll wait indefinitely to receive the ChanSync message. The
173✔
945
        // first message sent MUST be the ChanSync message.
173✔
946
        select {
173✔
947
        case msg := <-l.upstream:
173✔
948
                l.log.Tracef("Received msg=%v from peer(%x)", msg.MsgType(),
173✔
949
                        l.cfg.Peer.PubKey())
173✔
950

173✔
951
                remoteChanSyncMsg, ok := msg.(*lnwire.ChannelReestablish)
173✔
952
                if !ok {
173✔
953
                        return fmt.Errorf("first message sent to sync "+
×
954
                                "should be ChannelReestablish, instead "+
×
955
                                "received: %T", msg)
×
956
                }
×
957

958
                // If the remote party indicates that they think we haven't
959
                // done any state updates yet, then we'll retransmit the
960
                // channel_ready message first. We do this, as at this point
961
                // we can't be sure if they've really received the
962
                // ChannelReady message.
963
                if remoteChanSyncMsg.NextLocalCommitHeight == 1 &&
173✔
964
                        localChanSyncMsg.NextLocalCommitHeight == 1 &&
173✔
965
                        !l.channel.IsPending() {
340✔
966

167✔
967
                        l.log.Infof("resending ChannelReady message to peer")
167✔
968

167✔
969
                        nextRevocation, err := l.channel.NextRevocationKey()
167✔
970
                        if err != nil {
167✔
971
                                return fmt.Errorf("unable to create next "+
×
972
                                        "revocation: %v", err)
×
973
                        }
×
974

975
                        channelReadyMsg := lnwire.NewChannelReady(
167✔
976
                                l.ChanID(), nextRevocation,
167✔
977
                        )
167✔
978

167✔
979
                        // If this is a taproot channel, then we'll send the
167✔
980
                        // very same nonce that we sent above, as they should
167✔
981
                        // take the latest verification nonce we send.
167✔
982
                        if chanState.ChanType.IsTaproot() {
170✔
983
                                //nolint:ll
3✔
984
                                channelReadyMsg.NextLocalNonce = localChanSyncMsg.LocalNonce
3✔
985
                        }
3✔
986

987
                        // For channels that negotiated the option-scid-alias
988
                        // feature bit, ensure that we send over the alias in
989
                        // the channel_ready message. We'll send the first
990
                        // alias we find for the channel since it does not
991
                        // matter which alias we send. We'll error out if no
992
                        // aliases are found.
993
                        if l.negotiatedAliasFeature() {
170✔
994
                                aliases := l.getAliases()
3✔
995
                                if len(aliases) == 0 {
3✔
996
                                        // This shouldn't happen since we
×
997
                                        // always add at least one alias before
×
998
                                        // the channel reaches the link.
×
999
                                        return fmt.Errorf("no aliases found")
×
1000
                                }
×
1001

1002
                                // getAliases returns a copy of the alias slice
1003
                                // so it is ok to use a pointer to the first
1004
                                // entry.
1005
                                channelReadyMsg.AliasScid = &aliases[0]
3✔
1006
                        }
1007

1008
                        err = l.cfg.Peer.SendMessage(false, channelReadyMsg)
167✔
1009
                        if err != nil {
167✔
1010
                                return fmt.Errorf("unable to re-send "+
×
1011
                                        "ChannelReady: %v", err)
×
1012
                        }
×
1013
                }
1014

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

173✔
1018
                // This function will be called if an aux channel negotiator is
173✔
1019
                // present.
173✔
1020
                negotiatorClosure := func(n lnwallet.AuxChannelNegotiator) {
173✔
NEW
1021
                        fundingPoint := l.channel.ChannelPoint()
×
NEW
1022
                        auxBlob := l.FundingCustomBlob()
×
NEW
1023
                        cid := lnwire.NewChanIDFromOutPoint(fundingPoint)
×
NEW
1024

×
NEW
1025
                        remoteChanSyncMsg.AuxFeatures.WhenSome(
×
NEW
1026
                                func(features lnwire.AuxFeatureBits) {
×
NEW
1027
                                        err = n.ProcessReestablishFeatures(
×
NEW
1028
                                                cid, features,
×
NEW
1029
                                                auxBlob.UnwrapOr(nil),
×
NEW
1030
                                        )
×
NEW
1031
                                },
×
1032
                        )
1033
                }
1034
                if err != nil {
173✔
NEW
1035
                        return fmt.Errorf("failed to process aux reestablish "+
×
NEW
1036
                                "features: %v", err)
×
NEW
1037
                }
×
1038

1039
                // If we have an AuxChannelNegotiator and the remote sent aux
1040
                // features, process them. This is a blocking call that must
1041
                // complete before we continue with channel reestablishment.
1042
                if remoteChanSyncMsg.AuxFeatures.IsSome() {
173✔
NEW
1043
                        l.cfg.AuxChannelNegotiator.WhenSome(negotiatorClosure)
×
NEW
1044
                }
×
1045

1046
                var (
173✔
1047
                        openedCircuits []CircuitKey
173✔
1048
                        closedCircuits []CircuitKey
173✔
1049
                )
173✔
1050

173✔
1051
                // We've just received a ChanSync message from the remote
173✔
1052
                // party, so we'll process the message  in order to determine
173✔
1053
                // if we need to re-transmit any messages to the remote party.
173✔
1054
                ctx, cancel := l.cg.Create(ctx)
173✔
1055
                defer cancel()
173✔
1056
                msgsToReSend, openedCircuits, closedCircuits, err =
173✔
1057
                        l.channel.ProcessChanSyncMsg(ctx, remoteChanSyncMsg)
173✔
1058
                if err != nil {
176✔
1059
                        return err
3✔
1060
                }
3✔
1061

1062
                // Repopulate any identifiers for circuits that may have been
1063
                // opened or unclosed. This may happen if we needed to
1064
                // retransmit a commitment signature message.
1065
                l.openedCircuits = openedCircuits
173✔
1066
                l.closedCircuits = closedCircuits
173✔
1067

173✔
1068
                // Ensure that all packets have been have been removed from the
173✔
1069
                // link's mailbox.
173✔
1070
                if err := l.ackDownStreamPackets(); err != nil {
173✔
1071
                        return err
×
1072
                }
×
1073

1074
                if len(msgsToReSend) > 0 {
178✔
1075
                        l.log.Infof("sending %v updates to synchronize the "+
5✔
1076
                                "state", len(msgsToReSend))
5✔
1077
                }
5✔
1078

1079
                // If we have any messages to retransmit, we'll do so
1080
                // immediately so we return to a synchronized state as soon as
1081
                // possible.
1082
                for _, msg := range msgsToReSend {
184✔
1083
                        err := l.cfg.Peer.SendMessage(false, msg)
11✔
1084
                        if err != nil {
11✔
1085
                                l.log.Errorf("failed to send %v: %v",
×
1086
                                        msg.MsgType(), err)
×
1087
                        }
×
1088
                }
1089

1090
        case <-l.cg.Done():
3✔
1091
                return ErrLinkShuttingDown
3✔
1092
        }
1093

1094
        return nil
173✔
1095
}
1096

1097
// resolveFwdPkgs loads any forwarding packages for this link from disk, and
1098
// reprocesses them in order. The primary goal is to make sure that any HTLCs
1099
// we previously received are reinstated in memory, and forwarded to the switch
1100
// if necessary. After a restart, this will also delete any previously
1101
// completed packages.
1102
func (l *channelLink) resolveFwdPkgs(ctx context.Context) error {
216✔
1103
        fwdPkgs, err := l.channel.LoadFwdPkgs()
216✔
1104
        if err != nil {
217✔
1105
                return err
1✔
1106
        }
1✔
1107

1108
        l.log.Debugf("loaded %d fwd pks", len(fwdPkgs))
215✔
1109

215✔
1110
        for _, fwdPkg := range fwdPkgs {
224✔
1111
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
9✔
UNCOV
1112
                        return err
×
UNCOV
1113
                }
×
1114
        }
1115

1116
        // If any of our reprocessing steps require an update to the commitment
1117
        // txn, we initiate a state transition to capture all relevant changes.
1118
        if l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote) > 0 {
218✔
1119
                return l.updateCommitTx(ctx)
3✔
1120
        }
3✔
1121

1122
        return nil
215✔
1123
}
1124

1125
// resolveFwdPkg interprets the FwdState of the provided package, either
1126
// reprocesses any outstanding htlcs in the package, or performs garbage
1127
// collection on the package.
1128
func (l *channelLink) resolveFwdPkg(fwdPkg *channeldb.FwdPkg) error {
9✔
1129
        // Remove any completed packages to clear up space.
9✔
1130
        if fwdPkg.State == channeldb.FwdStateCompleted {
13✔
1131
                l.log.Debugf("removing completed fwd pkg for height=%d",
4✔
1132
                        fwdPkg.Height)
4✔
1133

4✔
1134
                err := l.channel.RemoveFwdPkgs(fwdPkg.Height)
4✔
1135
                if err != nil {
4✔
UNCOV
1136
                        l.log.Errorf("unable to remove fwd pkg for height=%d: "+
×
UNCOV
1137
                                "%v", fwdPkg.Height, err)
×
UNCOV
1138
                        return err
×
UNCOV
1139
                }
×
1140
        }
1141

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

1148
        // If the package is fully acked but not completed, it must still have
1149
        // settles and fails to propagate.
1150
        if !fwdPkg.SettleFailFilter.IsFull() {
12✔
1151
                l.processRemoteSettleFails(fwdPkg)
3✔
1152
        }
3✔
1153

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

6✔
1161
                // If the link failed during processing the adds, we must
6✔
1162
                // return to ensure we won't attempted to update the state
6✔
1163
                // further.
6✔
1164
                if l.failed {
6✔
1165
                        return fmt.Errorf("link failed while " +
×
1166
                                "processing remote adds")
×
1167
                }
×
1168
        }
1169

1170
        return nil
9✔
1171
}
1172

1173
// fwdPkgGarbager periodically reads all forwarding packages from disk and
1174
// removes those that can be discarded. It is safe to do this entirely in the
1175
// background, since all state is coordinated on disk. This also ensures the
1176
// link can continue to process messages and interleave database accesses.
1177
//
1178
// NOTE: This MUST be run as a goroutine.
1179
func (l *channelLink) fwdPkgGarbager() {
215✔
1180
        defer l.cg.WgDone()
215✔
1181

215✔
1182
        l.cfg.FwdPkgGCTicker.Resume()
215✔
1183
        defer l.cfg.FwdPkgGCTicker.Stop()
215✔
1184

215✔
1185
        if err := l.loadAndRemove(); err != nil {
215✔
1186
                l.log.Warnf("unable to run initial fwd pkgs gc: %v", err)
×
1187
        }
×
1188

1189
        for {
445✔
1190
                select {
230✔
1191
                case <-l.cfg.FwdPkgGCTicker.Ticks():
15✔
1192
                        if err := l.loadAndRemove(); err != nil {
30✔
1193
                                l.log.Warnf("unable to remove fwd pkgs: %v",
15✔
1194
                                        err)
15✔
1195
                                continue
15✔
1196
                        }
1197
                case <-l.cg.Done():
205✔
1198
                        return
205✔
1199
                }
1200
        }
1201
}
1202

1203
// loadAndRemove loads all the channels forwarding packages and determines if
1204
// they can be removed. It is called once before the FwdPkgGCTicker ticks so that
1205
// a longer tick interval can be used.
1206
func (l *channelLink) loadAndRemove() error {
230✔
1207
        fwdPkgs, err := l.channel.LoadFwdPkgs()
230✔
1208
        if err != nil {
245✔
1209
                return err
15✔
1210
        }
15✔
1211

1212
        var removeHeights []uint64
215✔
1213
        for _, fwdPkg := range fwdPkgs {
223✔
1214
                if fwdPkg.State != channeldb.FwdStateCompleted {
16✔
1215
                        continue
8✔
1216
                }
1217

1218
                removeHeights = append(removeHeights, fwdPkg.Height)
3✔
1219
        }
1220

1221
        // If removeHeights is empty, return early so we don't use a db
1222
        // transaction.
1223
        if len(removeHeights) == 0 {
430✔
1224
                return nil
215✔
1225
        }
215✔
1226

1227
        return l.channel.RemoveFwdPkgs(removeHeights...)
3✔
1228
}
1229

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

3✔
1235
        var errDataLoss *lnwallet.ErrCommitSyncLocalDataLoss
3✔
1236

3✔
1237
        switch {
3✔
1238
        case errors.Is(err, ErrLinkShuttingDown):
3✔
1239
                l.log.Debugf("unable to sync channel states, link is " +
3✔
1240
                        "shutting down")
3✔
1241
                return
3✔
1242

1243
        // We failed syncing the commit chains, probably because the remote has
1244
        // lost state. We should force close the channel.
1245
        case errors.Is(err, lnwallet.ErrCommitSyncRemoteDataLoss):
3✔
1246
                fallthrough
3✔
1247

1248
        // The remote sent us an invalid last commit secret, we should force
1249
        // close the channel.
1250
        // TODO(halseth): and permanently ban the peer?
1251
        case errors.Is(err, lnwallet.ErrInvalidLastCommitSecret):
3✔
1252
                fallthrough
3✔
1253

1254
        // The remote sent us a commit point different from what they sent us
1255
        // before.
1256
        // TODO(halseth): ban peer?
1257
        case errors.Is(err, lnwallet.ErrInvalidLocalUnrevokedCommitPoint):
3✔
1258
                // We'll fail the link and tell the peer to force close the
3✔
1259
                // channel. Note that the database state is not updated here,
3✔
1260
                // but will be updated when the close transaction is ready to
3✔
1261
                // avoid that we go down before storing the transaction in the
3✔
1262
                // db.
3✔
1263
                l.failf(
3✔
1264
                        LinkFailureError{
3✔
1265
                                code:          ErrSyncError,
3✔
1266
                                FailureAction: LinkFailureForceClose,
3✔
1267
                        },
3✔
1268
                        "unable to synchronize channel states: %v", err,
3✔
1269
                )
3✔
1270

1271
        // We have lost state and cannot safely force close the channel. Fail
1272
        // the channel and wait for the remote to hopefully force close it. The
1273
        // remote has sent us its latest unrevoked commitment point, and we'll
1274
        // store it in the database, such that we can attempt to recover the
1275
        // funds if the remote force closes the channel.
1276
        case errors.As(err, &errDataLoss):
3✔
1277
                err := l.channel.MarkDataLoss(
3✔
1278
                        errDataLoss.CommitPoint,
3✔
1279
                )
3✔
1280
                if err != nil {
3✔
1281
                        l.log.Errorf("unable to mark channel data loss: %v",
×
1282
                                err)
×
1283
                }
×
1284

1285
        // We determined the commit chains were not possible to sync. We
1286
        // cautiously fail the channel, but don't force close.
1287
        // TODO(halseth): can we safely force close in any cases where this
1288
        // error is returned?
1289
        case errors.Is(err, lnwallet.ErrCannotSyncCommitChains):
×
1290
                if err := l.channel.MarkBorked(); err != nil {
×
1291
                        l.log.Errorf("unable to mark channel borked: %v", err)
×
1292
                }
×
1293

1294
        // Other, unspecified error.
1295
        default:
×
1296
        }
1297

1298
        l.failf(
3✔
1299
                LinkFailureError{
3✔
1300
                        code:          ErrRecoveryError,
3✔
1301
                        FailureAction: LinkFailureForceNone,
3✔
1302
                },
3✔
1303
                "unable to synchronize channel states: %v", err,
3✔
1304
        )
3✔
1305
}
1306

1307
// htlcManager is the primary goroutine which drives a channel's commitment
1308
// update state-machine in response to messages received via several channels.
1309
// This goroutine reads messages from the upstream (remote) peer, and also from
1310
// downstream channel managed by the channel link. In the event that an htlc
1311
// needs to be forwarded, then send-only forward handler is used which sends
1312
// htlc packets to the switch. Additionally, this goroutine handles acting upon
1313
// all timeouts for any active HTLCs, manages the channel's revocation window,
1314
// and also the htlc trickle queue+timer for this active channels.
1315
//
1316
// NOTE: This MUST be run as a goroutine.
1317
func (l *channelLink) htlcManager(ctx context.Context) {
216✔
1318
        defer func() {
423✔
1319
                l.cfg.BatchTicker.Stop()
207✔
1320
                l.cg.WgDone()
207✔
1321
                l.log.Infof("exited")
207✔
1322
        }()
207✔
1323

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

216✔
1326
        // Notify any clients that the link is now in the switch via an
216✔
1327
        // ActiveLinkEvent. We'll also defer an inactive link notification for
216✔
1328
        // when the link exits to ensure that every active notification is
216✔
1329
        // matched by an inactive one.
216✔
1330
        l.cfg.NotifyActiveLink(l.ChannelPoint())
216✔
1331
        defer l.cfg.NotifyInactiveLinkEvent(l.ChannelPoint())
216✔
1332

216✔
1333
        // If the link is not started for the first time, we need to take extra
216✔
1334
        // steps to resume its state.
216✔
1335
        err := l.resumeLink(ctx)
216✔
1336
        if err != nil {
220✔
1337
                l.log.Errorf("resuming link failed: %v", err)
4✔
1338
                return
4✔
1339
        }
4✔
1340

1341
        // Now that we've received both channel_ready and channel reestablish,
1342
        // we can go ahead and send the active channel notification. We'll also
1343
        // defer the inactive notification for when the link exits to ensure
1344
        // that every active notification is matched by an inactive one.
1345
        l.cfg.NotifyActiveChannel(l.ChannelPoint())
215✔
1346
        defer l.cfg.NotifyInactiveChannel(l.ChannelPoint())
215✔
1347

215✔
1348
        for {
4,412✔
1349
                // We must always check if we failed at some point processing
4,197✔
1350
                // the last update before processing the next.
4,197✔
1351
                if l.failed {
4,213✔
1352
                        l.log.Errorf("link failed, exiting htlcManager")
16✔
1353
                        return
16✔
1354
                }
16✔
1355

1356
                // Pause or resume the batch ticker.
1357
                l.toggleBatchTicker()
4,184✔
1358

4,184✔
1359
                select {
4,184✔
1360
                // We have a new hook that needs to be run when we reach a clean
1361
                // channel state.
1362
                case hook := <-l.flushHooks.newTransients:
4✔
1363
                        if l.channel.IsChannelClean() {
7✔
1364
                                hook()
3✔
1365
                        } else {
7✔
1366
                                l.flushHooks.alloc(hook)
4✔
1367
                        }
4✔
1368

1369
                // We have a new hook that needs to be run when we have
1370
                // committed all of our updates.
1371
                case hook := <-l.outgoingCommitHooks.newTransients:
4✔
1372
                        if !l.channel.OweCommitment() {
7✔
1373
                                hook()
3✔
1374
                        } else {
4✔
1375
                                l.outgoingCommitHooks.alloc(hook)
1✔
1376
                        }
1✔
1377

1378
                // We have a new hook that needs to be run when our peer has
1379
                // committed all of their updates.
1380
                case hook := <-l.incomingCommitHooks.newTransients:
×
1381
                        if !l.channel.NeedCommitment() {
×
1382
                                hook()
×
1383
                        } else {
×
1384
                                l.incomingCommitHooks.alloc(hook)
×
1385
                        }
×
1386

1387
                // Our update fee timer has fired, so we'll check the network
1388
                // fee to see if we should adjust our commitment fee.
1389
                case <-l.updateFeeTimer.C:
4✔
1390
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
4✔
1391
                        err := l.handleUpdateFee(ctx)
4✔
1392
                        if err != nil {
4✔
1393
                                l.log.Errorf("failed to handle update fee: "+
×
1394
                                        "%v", err)
×
1395
                        }
×
1396

1397
                // The underlying channel has notified us of a unilateral close
1398
                // carried out by the remote peer. In the case of such an
1399
                // event, we'll wipe the channel state from the peer, and mark
1400
                // the contract as fully settled. Afterwards we can exit.
1401
                //
1402
                // TODO(roasbeef): add force closure? also breach?
1403
                case <-l.cfg.ChainEvents.RemoteUnilateralClosure:
3✔
1404
                        l.log.Warnf("remote peer has closed on-chain")
3✔
1405

3✔
1406
                        // TODO(roasbeef): remove all together
3✔
1407
                        go func() {
6✔
1408
                                chanPoint := l.channel.ChannelPoint()
3✔
1409
                                l.cfg.Peer.WipeChannel(&chanPoint)
3✔
1410
                        }()
3✔
1411

1412
                        return
3✔
1413

1414
                case <-l.cfg.BatchTicker.Ticks():
203✔
1415
                        // Attempt to extend the remote commitment chain
203✔
1416
                        // including all the currently pending entries. If the
203✔
1417
                        // send was unsuccessful, then abandon the update,
203✔
1418
                        // waiting for the revocation window to open up.
203✔
1419
                        if !l.updateCommitTxOrFail(ctx) {
203✔
1420
                                return
×
1421
                        }
×
1422

1423
                case <-l.cfg.PendingCommitTicker.Ticks():
1✔
1424
                        l.failf(
1✔
1425
                                LinkFailureError{
1✔
1426
                                        code:          ErrRemoteUnresponsive,
1✔
1427
                                        FailureAction: LinkFailureDisconnect,
1✔
1428
                                },
1✔
1429
                                "unable to complete dance",
1✔
1430
                        )
1✔
1431
                        return
1✔
1432

1433
                // A message from the switch was just received. This indicates
1434
                // that the link is an intermediate hop in a multi-hop HTLC
1435
                // circuit.
1436
                case pkt := <-l.downstream:
524✔
1437
                        l.handleDownstreamPkt(ctx, pkt)
524✔
1438

1439
                // A message from the connected peer was just received. This
1440
                // indicates that we have a new incoming HTLC, either directly
1441
                // for us, or part of a multi-hop HTLC circuit.
1442
                case msg := <-l.upstream:
3,202✔
1443
                        l.handleUpstreamMsg(ctx, msg)
3,202✔
1444

1445
                // A htlc resolution is received. This means that we now have a
1446
                // resolution for a previously accepted htlc.
1447
                case hodlItem := <-l.hodlQueue.ChanOut():
58✔
1448
                        err := l.handleHtlcResolution(ctx, hodlItem)
58✔
1449
                        if err != nil {
59✔
1450
                                l.log.Errorf("failed to handle htlc "+
1✔
1451
                                        "resolution: %v", err)
1✔
1452
                        }
1✔
1453

1454
                // A user-initiated quiescence request is received. We now
1455
                // forward it to the quiescer.
1456
                case qReq := <-l.quiescenceReqs:
4✔
1457
                        err := l.handleQuiescenceReq(qReq)
4✔
1458
                        if err != nil {
4✔
1459
                                l.log.Errorf("failed handle quiescence "+
×
1460
                                        "req: %v", err)
×
1461
                        }
×
1462

1463
                case <-l.cg.Done():
192✔
1464
                        return
192✔
1465
                }
1466
        }
1467
}
1468

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

58✔
1475
        // Try to read all waiting resolution messages, so that they can all be
58✔
1476
        // processed in a single commitment tx update.
58✔
1477
        htlcResolution := firstResolution
58✔
1478
loop:
58✔
1479
        for {
116✔
1480
                // Lookup all hodl htlcs that can be failed or settled with this event.
58✔
1481
                // The hodl htlc must be present in the map.
58✔
1482
                circuitKey := htlcResolution.CircuitKey()
58✔
1483
                hodlHtlc, ok := l.hodlMap[circuitKey]
58✔
1484
                if !ok {
58✔
1485
                        return fmt.Errorf("hodl htlc not found: %v", circuitKey)
×
1486
                }
×
1487

1488
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
58✔
1489
                        return err
×
1490
                }
×
1491

1492
                // Clean up hodl map.
1493
                delete(l.hodlMap, circuitKey)
58✔
1494

58✔
1495
                select {
58✔
1496
                case item := <-l.hodlQueue.ChanOut():
3✔
1497
                        htlcResolution = item.(invoices.HtlcResolution)
3✔
1498

1499
                // No need to process it if the link is broken.
1500
                case <-l.cg.Done():
×
1501
                        return ErrLinkShuttingDown
×
1502

1503
                default:
58✔
1504
                        break loop
58✔
1505
                }
1506
        }
1507

1508
        // Update the commitment tx.
1509
        if err := l.updateCommitTx(ctx); err != nil {
59✔
1510
                return err
1✔
1511
        }
1✔
1512

1513
        return nil
57✔
1514
}
1515

1516
// processHtlcResolution applies a received htlc resolution to the provided
1517
// htlc. When this function returns without an error, the commit tx should be
1518
// updated.
1519
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1520
        htlc hodlHtlc) error {
204✔
1521

204✔
1522
        circuitKey := resolution.CircuitKey()
204✔
1523

204✔
1524
        // Determine required action for the resolution based on the type of
204✔
1525
        // resolution we have received.
204✔
1526
        switch res := resolution.(type) {
204✔
1527
        // Settle htlcs that returned a settle resolution using the preimage
1528
        // in the resolution.
1529
        case *invoices.HtlcSettleResolution:
200✔
1530
                l.log.Debugf("received settle resolution for %v "+
200✔
1531
                        "with outcome: %v", circuitKey, res.Outcome)
200✔
1532

200✔
1533
                return l.settleHTLC(
200✔
1534
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
200✔
1535
                )
200✔
1536

1537
        // For htlc failures, we get the relevant failure message based
1538
        // on the failure resolution and then fail the htlc.
1539
        case *invoices.HtlcFailResolution:
7✔
1540
                l.log.Debugf("received cancel resolution for "+
7✔
1541
                        "%v with outcome: %v", circuitKey, res.Outcome)
7✔
1542

7✔
1543
                // Get the lnwire failure message based on the resolution
7✔
1544
                // result.
7✔
1545
                failure := getResolutionFailure(res, htlc.add.Amount)
7✔
1546

7✔
1547
                l.sendHTLCError(
7✔
1548
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
7✔
1549
                        true,
7✔
1550
                )
7✔
1551
                return nil
7✔
1552

1553
        // Fail if we do not get a settle of fail resolution, since we
1554
        // are only expecting to handle settles and fails.
1555
        default:
×
1556
                return fmt.Errorf("unknown htlc resolution type: %T",
×
1557
                        resolution)
×
1558
        }
1559
}
1560

1561
// getResolutionFailure returns the wire message that a htlc resolution should
1562
// be failed with.
1563
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1564
        amount lnwire.MilliSatoshi) *LinkError {
7✔
1565

7✔
1566
        // If the resolution has been resolved as part of a MPP timeout,
7✔
1567
        // we need to fail the htlc with lnwire.FailMppTimeout.
7✔
1568
        if resolution.Outcome == invoices.ResultMppTimeout {
7✔
1569
                return NewDetailedLinkError(
×
1570
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
1571
                )
×
1572
        }
×
1573

1574
        // If the htlc is not a MPP timeout, we fail it with
1575
        // FailIncorrectDetails. This error is sent for invoice payment
1576
        // failures such as underpayment/ expiry too soon and hodl invoices
1577
        // (which return FailIncorrectDetails to avoid leaking information).
1578
        incorrectDetails := lnwire.NewFailIncorrectDetails(
7✔
1579
                amount, uint32(resolution.AcceptHeight),
7✔
1580
        )
7✔
1581

7✔
1582
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
7✔
1583
}
1584

1585
// randomFeeUpdateTimeout returns a random timeout between the bounds defined
1586
// within the link's configuration that will be used to determine when the link
1587
// should propose an update to its commitment fee rate.
1588
func (l *channelLink) randomFeeUpdateTimeout() time.Duration {
220✔
1589
        lower := int64(l.cfg.MinUpdateTimeout)
220✔
1590
        upper := int64(l.cfg.MaxUpdateTimeout)
220✔
1591
        return time.Duration(prand.Int63n(upper-lower) + lower)
220✔
1592
}
220✔
1593

1594
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1595
// downstream HTLC Switch.
1596
func (l *channelLink) handleDownstreamUpdateAdd(ctx context.Context,
1597
        pkt *htlcPacket) error {
483✔
1598

483✔
1599
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
483✔
1600
        if !ok {
483✔
1601
                return errors.New("not an UpdateAddHTLC packet")
×
1602
        }
×
1603

1604
        // If we are flushing the link in the outgoing direction or we have
1605
        // already sent Stfu, then we can't add new htlcs to the link and we
1606
        // need to bounce it.
1607
        if l.IsFlushing(Outgoing) || !l.quiescer.CanSendUpdates() {
483✔
1608
                l.mailBox.FailAdd(pkt)
×
1609

×
1610
                return NewDetailedLinkError(
×
1611
                        &lnwire.FailTemporaryChannelFailure{},
×
1612
                        OutgoingFailureLinkNotEligible,
×
1613
                )
×
1614
        }
×
1615

1616
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1617
        // arbitrary delays between the switch adding an ADD to the
1618
        // mailbox, and the HTLC being added to the commitment state.
1619
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
483✔
1620
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
1621
                l.mailBox.AckPacket(pkt.inKey())
×
1622
                return nil
×
1623
        }
×
1624

1625
        // Check if we can add the HTLC here without exceededing the max fee
1626
        // exposure threshold.
1627
        if l.isOverexposedWithHtlc(htlc, false) {
487✔
1628
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1629
                        "exposure exceeded")
4✔
1630

4✔
1631
                l.mailBox.FailAdd(pkt)
4✔
1632

4✔
1633
                return NewDetailedLinkError(
4✔
1634
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1635
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1636
                )
4✔
1637
        }
4✔
1638

1639
        // A new payment has been initiated via the downstream channel,
1640
        // so we add the new HTLC to our local log, then update the
1641
        // commitment chains.
1642
        htlc.ChanID = l.ChanID()
479✔
1643
        openCircuitRef := pkt.inKey()
479✔
1644

479✔
1645
        // We enforce the fee buffer for the commitment transaction because
479✔
1646
        // we are in control of adding this htlc. Nothing has locked-in yet so
479✔
1647
        // we can securely enforce the fee buffer which is only relevant if we
479✔
1648
        // are the initiator of the channel.
479✔
1649
        index, err := l.channel.AddHTLC(htlc, &openCircuitRef)
479✔
1650
        if err != nil {
482✔
1651
                // The HTLC was unable to be added to the state machine,
3✔
1652
                // as a result, we'll signal the switch to cancel the
3✔
1653
                // pending payment.
3✔
1654
                l.log.Warnf("Unable to handle downstream add HTLC: %v",
3✔
1655
                        err)
3✔
1656

3✔
1657
                // Remove this packet from the link's mailbox, this
3✔
1658
                // prevents it from being reprocessed if the link
3✔
1659
                // restarts and resets it mailbox. If this response
3✔
1660
                // doesn't make it back to the originating link, it will
3✔
1661
                // be rejected upon attempting to reforward the Add to
3✔
1662
                // the switch, since the circuit was never fully opened,
3✔
1663
                // and the forwarding package shows it as
3✔
1664
                // unacknowledged.
3✔
1665
                l.mailBox.FailAdd(pkt)
3✔
1666

3✔
1667
                return NewDetailedLinkError(
3✔
1668
                        lnwire.NewTemporaryChannelFailure(nil),
3✔
1669
                        OutgoingFailureDownstreamHtlcAdd,
3✔
1670
                )
3✔
1671
        }
3✔
1672

1673
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
478✔
1674
                "local_log_index=%v, pend_updates=%v",
478✔
1675
                htlc.PaymentHash[:], index,
478✔
1676
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
478✔
1677

478✔
1678
        pkt.outgoingChanID = l.ShortChanID()
478✔
1679
        pkt.outgoingHTLCID = index
478✔
1680
        htlc.ID = index
478✔
1681

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

478✔
1685
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
478✔
1686
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
478✔
1687

478✔
1688
        err = l.cfg.Peer.SendMessage(false, htlc)
478✔
1689
        if err != nil {
478✔
1690
                l.log.Errorf("failed to send UpdateAddHTLC: %v", err)
×
1691
        }
×
1692

1693
        // Send a forward event notification to htlcNotifier.
1694
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
478✔
1695
                newHtlcKey(pkt),
478✔
1696
                HtlcInfo{
478✔
1697
                        IncomingTimeLock: pkt.incomingTimeout,
478✔
1698
                        IncomingAmt:      pkt.incomingAmount,
478✔
1699
                        OutgoingTimeLock: htlc.Expiry,
478✔
1700
                        OutgoingAmt:      htlc.Amount,
478✔
1701
                },
478✔
1702
                getEventType(pkt),
478✔
1703
        )
478✔
1704

478✔
1705
        l.tryBatchUpdateCommitTx(ctx)
478✔
1706

478✔
1707
        return nil
478✔
1708
}
1709

1710
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1711
// Switch. Possible messages sent by the switch include requests to forward new
1712
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1713
// cleared HTLCs with the upstream peer.
1714
//
1715
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1716
func (l *channelLink) handleDownstreamPkt(ctx context.Context,
1717
        pkt *htlcPacket) {
524✔
1718

524✔
1719
        if pkt.htlc.MsgType().IsChannelUpdate() &&
524✔
1720
                !l.quiescer.CanSendUpdates() {
524✔
1721

×
1722
                l.log.Warnf("unable to process channel update. "+
×
1723
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1724

×
1725
                return
×
1726
        }
×
1727

1728
        switch htlc := pkt.htlc.(type) {
524✔
1729
        case *lnwire.UpdateAddHTLC:
483✔
1730
                // Handle add message. The returned error can be ignored,
483✔
1731
                // because it is also sent through the mailbox.
483✔
1732
                _ = l.handleDownstreamUpdateAdd(ctx, pkt)
483✔
1733

1734
        case *lnwire.UpdateFulfillHTLC:
26✔
1735
                l.processLocalUpdateFulfillHTLC(ctx, pkt, htlc)
26✔
1736

1737
        case *lnwire.UpdateFailHTLC:
21✔
1738
                l.processLocalUpdateFailHTLC(ctx, pkt, htlc)
21✔
1739
        }
1740
}
1741

1742
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1743
// full.
1744
func (l *channelLink) tryBatchUpdateCommitTx(ctx context.Context) {
478✔
1745
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
478✔
1746
        if pending < uint64(l.cfg.BatchSize) {
936✔
1747
                return
458✔
1748
        }
458✔
1749

1750
        l.updateCommitTxOrFail(ctx)
23✔
1751
}
1752

1753
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1754
// associated with this packet. If successful in doing so, it will also purge
1755
// the open circuit from the circuit map and remove the packet from the link's
1756
// mailbox.
1757
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
2✔
1758
        inKey := pkt.inKey()
2✔
1759

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

2✔
1763
        // If the htlc packet doesn't have a source reference, it is unsafe to
2✔
1764
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
2✔
1765
        if pkt.sourceRef == nil {
3✔
1766
                l.log.Errorf("unable to cleanup response for incoming "+
1✔
1767
                        "circuit-key=%v, does not contain source reference",
1✔
1768
                        inKey)
1✔
1769
                return
1✔
1770
        }
1✔
1771

1772
        // If the source reference is present,  we will try to prevent this link
1773
        // from resending the packet to the switch. To do so, we ack the AddRef
1774
        // of the incoming HTLC belonging to this link.
1775
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
1✔
1776
        if err != nil {
1✔
1777
                l.log.Errorf("unable to ack AddRef for incoming "+
×
1778
                        "circuit-key=%v: %v", inKey, err)
×
1779

×
1780
                // If this operation failed, it is unsafe to attempt removal of
×
1781
                // the destination reference or circuit, so we exit early. The
×
1782
                // cleanup may proceed with a different packet in the future
×
1783
                // that succeeds on this step.
×
1784
                return
×
1785
        }
×
1786

1787
        // Now that we know this link will stop retransmitting Adds to the
1788
        // switch, we can begin to teardown the response reference and circuit
1789
        // map.
1790
        //
1791
        // If the packet includes a destination reference, then a response for
1792
        // this HTLC was locked into the outgoing channel. Attempt to remove
1793
        // this reference, so we stop retransmitting the response internally.
1794
        // Even if this fails, we will proceed in trying to delete the circuit.
1795
        // When retransmitting responses, the destination references will be
1796
        // cleaned up if an open circuit is not found in the circuit map.
1797
        if pkt.destRef != nil {
1✔
1798
                err := l.channel.AckSettleFails(*pkt.destRef)
×
1799
                if err != nil {
×
1800
                        l.log.Errorf("unable to ack SettleFailRef "+
×
1801
                                "for incoming circuit-key=%v: %v",
×
1802
                                inKey, err)
×
1803
                }
×
1804
        }
1805

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

1✔
1808
        // With all known references acked, we can now safely delete the circuit
1✔
1809
        // from the switch's circuit map, as the state is no longer needed.
1✔
1810
        err = l.cfg.Circuits.DeleteCircuits(inKey)
1✔
1811
        if err != nil {
1✔
1812
                l.log.Errorf("unable to delete circuit for "+
×
1813
                        "circuit-key=%v: %v", inKey, err)
×
1814
        }
×
1815
}
1816

1817
// handleUpstreamMsg processes wire messages related to commitment state
1818
// updates from the upstream peer. The upstream peer is the peer whom we have a
1819
// direct channel with, updating our respective commitment chains.
1820
func (l *channelLink) handleUpstreamMsg(ctx context.Context,
1821
        msg lnwire.Message) {
3,202✔
1822

3,202✔
1823
        l.log.Tracef("receive upstream msg %v, handling now... ", msg.MsgType())
3,202✔
1824
        defer l.log.Tracef("handled upstream msg %v", msg.MsgType())
3,202✔
1825

3,202✔
1826
        // First check if the message is an update and we are capable of
3,202✔
1827
        // receiving updates right now.
3,202✔
1828
        if msg.MsgType().IsChannelUpdate() && !l.quiescer.CanRecvUpdates() {
3,202✔
1829
                l.stfuFailf("update received after stfu: %T", msg)
×
1830
                return
×
1831
        }
×
1832

1833
        var err error
3,202✔
1834

3,202✔
1835
        switch msg := msg.(type) {
3,202✔
1836
        case *lnwire.UpdateAddHTLC:
453✔
1837
                err = l.processRemoteUpdateAddHTLC(msg)
453✔
1838

1839
        case *lnwire.UpdateFulfillHTLC:
230✔
1840
                err = l.processRemoteUpdateFulfillHTLC(msg)
230✔
1841

1842
        case *lnwire.UpdateFailMalformedHTLC:
6✔
1843
                err = l.processRemoteUpdateFailMalformedHTLC(msg)
6✔
1844

1845
        case *lnwire.UpdateFailHTLC:
123✔
1846
                err = l.processRemoteUpdateFailHTLC(msg)
123✔
1847

1848
        case *lnwire.CommitSig:
1,205✔
1849
                err = l.processRemoteCommitSig(ctx, msg)
1,205✔
1850

1851
        case *lnwire.RevokeAndAck:
1,194✔
1852
                err = l.processRemoteRevokeAndAck(ctx, msg)
1,194✔
1853

1854
        case *lnwire.UpdateFee:
3✔
1855
                err = l.processRemoteUpdateFee(msg)
3✔
1856

1857
        case *lnwire.Stfu:
5✔
1858
                err = l.handleStfu(msg)
5✔
1859
                if err != nil {
5✔
1860
                        l.stfuFailf("handleStfu: %v", err)
×
1861
                }
×
1862

1863
        // In the case where we receive a warning message from our peer, just
1864
        // log it and move on. We choose not to disconnect from our peer,
1865
        // although we "MAY" do so according to the specification.
1866
        case *lnwire.Warning:
1✔
1867
                l.log.Warnf("received warning message from peer: %v",
1✔
1868
                        msg.Warning())
1✔
1869

1870
        case *lnwire.Error:
2✔
1871
                l.processRemoteError(msg)
2✔
1872

1873
        default:
×
1874
                l.log.Warnf("received unknown message of type %T", msg)
×
1875
        }
1876

1877
        if err != nil {
3,207✔
1878
                l.log.Errorf("failed to process remote %v: %v", msg.MsgType(),
5✔
1879
                        err)
5✔
1880
        }
5✔
1881
}
1882

1883
// handleStfu implements the top-level logic for handling the Stfu message from
1884
// our peer.
1885
func (l *channelLink) handleStfu(stfu *lnwire.Stfu) error {
5✔
1886
        if !l.noDanglingUpdates(lntypes.Remote) {
5✔
1887
                return ErrPendingRemoteUpdates
×
1888
        }
×
1889
        err := l.quiescer.RecvStfu(*stfu)
5✔
1890
        if err != nil {
5✔
1891
                return err
×
1892
        }
×
1893

1894
        // If we can immediately send an Stfu response back, we will.
1895
        if l.noDanglingUpdates(lntypes.Local) {
9✔
1896
                return l.quiescer.SendOwedStfu()
4✔
1897
        }
4✔
1898

1899
        return nil
1✔
1900
}
1901

1902
// stfuFailf fails the link in the case where the requirements of the quiescence
1903
// protocol are violated. In all cases we opt to drop the connection as only
1904
// link state (as opposed to channel state) is affected.
1905
func (l *channelLink) stfuFailf(format string, args ...interface{}) {
×
1906
        l.failf(LinkFailureError{
×
1907
                code:             ErrStfuViolation,
×
1908
                FailureAction:    LinkFailureDisconnect,
×
1909
                PermanentFailure: false,
×
1910
                Warning:          true,
×
1911
        }, format, args...)
×
1912
}
×
1913

1914
// noDanglingUpdates returns true when there are 0 updates that were originally
1915
// issued by whose on either the Local or Remote commitment transaction.
1916
func (l *channelLink) noDanglingUpdates(whose lntypes.ChannelParty) bool {
1,210✔
1917
        pendingOnLocal := l.channel.NumPendingUpdates(
1,210✔
1918
                whose, lntypes.Local,
1,210✔
1919
        )
1,210✔
1920
        pendingOnRemote := l.channel.NumPendingUpdates(
1,210✔
1921
                whose, lntypes.Remote,
1,210✔
1922
        )
1,210✔
1923

1,210✔
1924
        return pendingOnLocal == 0 && pendingOnRemote == 0
1,210✔
1925
}
1,210✔
1926

1927
// ackDownStreamPackets is responsible for removing htlcs from a link's mailbox
1928
// for packets delivered from server, and cleaning up any circuits closed by
1929
// signing a previous commitment txn. This method ensures that the circuits are
1930
// removed from the circuit map before removing them from the link's mailbox,
1931
// otherwise it could be possible for some circuit to be missed if this link
1932
// flaps.
1933
func (l *channelLink) ackDownStreamPackets() error {
1,384✔
1934
        // First, remove the downstream Add packets that were included in the
1,384✔
1935
        // previous commitment signature. This will prevent the Adds from being
1,384✔
1936
        // replayed if this link disconnects.
1,384✔
1937
        for _, inKey := range l.openedCircuits {
1,851✔
1938
                // In order to test the sphinx replay logic of the remote
467✔
1939
                // party, unsafe replay does not acknowledge the packets from
467✔
1940
                // the mailbox. We can then force a replay of any Add packets
467✔
1941
                // held in memory by disconnecting and reconnecting the link.
467✔
1942
                if l.cfg.UnsafeReplay {
470✔
1943
                        continue
3✔
1944
                }
1945

1946
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
467✔
1947
                l.mailBox.AckPacket(inKey)
467✔
1948
        }
1949

1950
        // Now, we will delete all circuits closed by the previous commitment
1951
        // signature, which is the result of downstream Settle/Fail packets. We
1952
        // batch them here to ensure circuits are closed atomically and for
1953
        // performance.
1954
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
1,384✔
1955
        switch err {
1,384✔
1956
        case nil:
1,384✔
1957
                // Successful deletion.
1958

1959
        default:
×
1960
                l.log.Errorf("unable to delete %d circuits: %v",
×
1961
                        len(l.closedCircuits), err)
×
1962
                return err
×
1963
        }
1964

1965
        // With the circuits removed from memory and disk, we now ack any
1966
        // Settle/Fails in the mailbox to ensure they do not get redelivered
1967
        // after startup. If forgive is enabled and we've reached this point,
1968
        // the circuits must have been removed at some point, so it is now safe
1969
        // to un-queue the corresponding Settle/Fails.
1970
        for _, inKey := range l.closedCircuits {
1,426✔
1971
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
42✔
1972
                        inKey)
42✔
1973
                l.mailBox.AckPacket(inKey)
42✔
1974
        }
42✔
1975

1976
        // Lastly, reset our buffers to be empty while keeping any acquired
1977
        // growth in the backing array.
1978
        l.openedCircuits = l.openedCircuits[:0]
1,384✔
1979
        l.closedCircuits = l.closedCircuits[:0]
1,384✔
1980

1,384✔
1981
        return nil
1,384✔
1982
}
1983

1984
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
1985
// the link.
1986
func (l *channelLink) updateCommitTxOrFail(ctx context.Context) bool {
1,256✔
1987
        err := l.updateCommitTx(ctx)
1,256✔
1988
        switch {
1,256✔
1989
        // No error encountered, success.
1990
        case err == nil:
1,246✔
1991

1992
        // A duplicate keystone error should be resolved and is not fatal, so
1993
        // we won't send an Error message to the peer.
1994
        case errors.Is(err, ErrDuplicateKeystone):
×
1995
                l.failf(LinkFailureError{code: ErrCircuitError},
×
1996
                        "temporary circuit error: %v", err)
×
1997
                return false
×
1998

1999
        // Any other error is treated results in an Error message being sent to
2000
        // the peer.
2001
        default:
10✔
2002
                l.failf(LinkFailureError{code: ErrInternalError},
10✔
2003
                        "unable to update commitment: %v", err)
10✔
2004
                return false
10✔
2005
        }
2006

2007
        return true
1,246✔
2008
}
2009

2010
// updateCommitTx signs, then sends an update to the remote peer adding a new
2011
// commitment to their commitment chain which includes all the latest updates
2012
// we've received+processed up to this point.
2013
func (l *channelLink) updateCommitTx(ctx context.Context) error {
1,314✔
2014
        // Preemptively write all pending keystones to disk, just in case the
1,314✔
2015
        // HTLCs we have in memory are included in the subsequent attempt to
1,314✔
2016
        // sign a commitment state.
1,314✔
2017
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
1,314✔
2018
        if err != nil {
1,314✔
2019
                // If ErrDuplicateKeystone is returned, the caller will catch
×
2020
                // it.
×
2021
                return err
×
2022
        }
×
2023

2024
        // Reset the batch, but keep the backing buffer to avoid reallocating.
2025
        l.keystoneBatch = l.keystoneBatch[:0]
1,314✔
2026

1,314✔
2027
        // If hodl.Commit mode is active, we will refrain from attempting to
1,314✔
2028
        // commit any in-memory modifications to the channel state. Exiting here
1,314✔
2029
        // permits testing of either the switch or link's ability to trim
1,314✔
2030
        // circuits that have been opened, but unsuccessfully committed.
1,314✔
2031
        if l.cfg.HodlMask.Active(hodl.Commit) {
1,321✔
2032
                l.log.Warnf(hodl.Commit.Warning())
7✔
2033
                return nil
7✔
2034
        }
7✔
2035

2036
        ctx, done := l.cg.Create(ctx)
1,310✔
2037
        defer done()
1,310✔
2038

1,310✔
2039
        newCommit, err := l.channel.SignNextCommitment(ctx)
1,310✔
2040
        if err == lnwallet.ErrNoWindow {
1,409✔
2041
                l.cfg.PendingCommitTicker.Resume()
99✔
2042
                l.log.Trace("PendingCommitTicker resumed")
99✔
2043

99✔
2044
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
99✔
2045
                l.log.Tracef("revocation window exhausted, unable to send: "+
99✔
2046
                        "%v, pend_updates=%v, dangling_closes%v", n,
99✔
2047
                        lnutils.SpewLogClosure(l.openedCircuits),
99✔
2048
                        lnutils.SpewLogClosure(l.closedCircuits))
99✔
2049

99✔
2050
                return nil
99✔
2051
        } else if err != nil {
1,313✔
2052
                return err
×
2053
        }
×
2054

2055
        if err := l.ackDownStreamPackets(); err != nil {
1,214✔
2056
                return err
×
2057
        }
×
2058

2059
        l.cfg.PendingCommitTicker.Pause()
1,214✔
2060
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
1,214✔
2061

1,214✔
2062
        // The remote party now has a new pending commitment, so we'll update
1,214✔
2063
        // the contract court to be aware of this new set (the prior old remote
1,214✔
2064
        // pending).
1,214✔
2065
        newUpdate := &contractcourt.ContractUpdate{
1,214✔
2066
                HtlcKey: contractcourt.RemotePendingHtlcSet,
1,214✔
2067
                Htlcs:   newCommit.PendingHTLCs,
1,214✔
2068
        }
1,214✔
2069
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,214✔
2070
        if err != nil {
1,214✔
2071
                l.log.Errorf("unable to notify contract update: %v", err)
×
2072
                return err
×
2073
        }
×
2074

2075
        select {
1,214✔
2076
        case <-l.cg.Done():
11✔
2077
                return ErrLinkShuttingDown
11✔
2078
        default:
1,203✔
2079
        }
2080

2081
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
1,203✔
2082
        if err != nil {
1,203✔
2083
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
2084
        }
×
2085

2086
        commitSig := &lnwire.CommitSig{
1,203✔
2087
                ChanID:        l.ChanID(),
1,203✔
2088
                CommitSig:     newCommit.CommitSig,
1,203✔
2089
                HtlcSigs:      newCommit.HtlcSigs,
1,203✔
2090
                PartialSig:    newCommit.PartialSig,
1,203✔
2091
                CustomRecords: auxBlobRecords,
1,203✔
2092
        }
1,203✔
2093
        err = l.cfg.Peer.SendMessage(false, commitSig)
1,203✔
2094
        if err != nil {
1,203✔
UNCOV
2095
                l.log.Errorf("failed to send CommitSig: %v", err)
×
UNCOV
2096
        }
×
2097

2098
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
2099
        // of commit hooks.
2100
        l.RWMutex.Lock()
1,203✔
2101
        l.outgoingCommitHooks.invoke()
1,203✔
2102
        l.RWMutex.Unlock()
1,203✔
2103

1,203✔
2104
        return nil
1,203✔
2105
}
2106

2107
// Peer returns the representation of remote peer with which we have the
2108
// channel link opened.
2109
//
2110
// NOTE: Part of the ChannelLink interface.
2111
func (l *channelLink) PeerPubKey() [33]byte {
444✔
2112
        return l.cfg.Peer.PubKey()
444✔
2113
}
444✔
2114

2115
// ChannelPoint returns the channel outpoint for the channel link.
2116
// NOTE: Part of the ChannelLink interface.
2117
func (l *channelLink) ChannelPoint() wire.OutPoint {
853✔
2118
        return l.channel.ChannelPoint()
853✔
2119
}
853✔
2120

2121
// ShortChanID returns the short channel ID for the channel link. The short
2122
// channel ID encodes the exact location in the main chain that the original
2123
// funding output can be found.
2124
//
2125
// NOTE: Part of the ChannelLink interface.
2126
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
4,253✔
2127
        l.RLock()
4,253✔
2128
        defer l.RUnlock()
4,253✔
2129

4,253✔
2130
        return l.channel.ShortChanID()
4,253✔
2131
}
4,253✔
2132

2133
// UpdateShortChanID updates the short channel ID for a link. This may be
2134
// required in the event that a link is created before the short chan ID for it
2135
// is known, or a re-org occurs, and the funding transaction changes location
2136
// within the chain.
2137
//
2138
// NOTE: Part of the ChannelLink interface.
2139
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
3✔
2140
        chanID := l.ChanID()
3✔
2141

3✔
2142
        // Refresh the channel state's short channel ID by loading it from disk.
3✔
2143
        // This ensures that the channel state accurately reflects the updated
3✔
2144
        // short channel ID.
3✔
2145
        err := l.channel.State().Refresh()
3✔
2146
        if err != nil {
3✔
2147
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
2148
                        "%v", chanID, err)
×
2149
                return hop.Source, err
×
2150
        }
×
2151

2152
        return hop.Source, nil
3✔
2153
}
2154

2155
// ChanID returns the channel ID for the channel link. The channel ID is a more
2156
// compact representation of a channel's full outpoint.
2157
//
2158
// NOTE: Part of the ChannelLink interface.
2159
func (l *channelLink) ChanID() lnwire.ChannelID {
3,943✔
2160
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
3,943✔
2161
}
3,943✔
2162

2163
// Bandwidth returns the total amount that can flow through the channel link at
2164
// this given instance. The value returned is expressed in millisatoshi and can
2165
// be used by callers when making forwarding decisions to determine if a link
2166
// can accept an HTLC.
2167
//
2168
// NOTE: Part of the ChannelLink interface.
2169
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
814✔
2170
        // Get the balance available on the channel for new HTLCs. This takes
814✔
2171
        // the channel reserve into account so HTLCs up to this value won't
814✔
2172
        // violate it.
814✔
2173
        return l.channel.AvailableBalance()
814✔
2174
}
814✔
2175

2176
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2177
// amount provided to the link. This check does not reserve a space, since
2178
// forwards or other payments may use the available slot, so it should be
2179
// considered best-effort.
2180
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
3✔
2181
        return l.channel.MayAddOutgoingHtlc(amt)
3✔
2182
}
3✔
2183

2184
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2185
// method.
2186
//
2187
// NOTE: Part of the dustHandler interface.
2188
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2189
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
2,526✔
2190

2,526✔
2191
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
2,526✔
2192
}
2,526✔
2193

2194
// getFeeRate is a wrapper method that retrieves the underlying channel's
2195
// feerate.
2196
//
2197
// NOTE: Part of the dustHandler interface.
2198
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
672✔
2199
        return l.channel.CommitFeeRate()
672✔
2200
}
672✔
2201

2202
// getDustClosure returns a closure that can be used by the switch or mailbox
2203
// to evaluate whether a given HTLC is dust.
2204
//
2205
// NOTE: Part of the dustHandler interface.
2206
func (l *channelLink) getDustClosure() dustClosure {
1,602✔
2207
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
1,602✔
2208
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
1,602✔
2209
        chanType := l.channel.State().ChanType
1,602✔
2210

1,602✔
2211
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
1,602✔
2212
}
1,602✔
2213

2214
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2215
// is used so that the Switch can have access to the commitment fee without
2216
// needing to have a *LightningChannel. This doesn't include dust.
2217
//
2218
// NOTE: Part of the dustHandler interface.
2219
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
1,897✔
2220
        if remote {
2,864✔
2221
                return l.channel.State().RemoteCommitment.CommitFee
967✔
2222
        }
967✔
2223

2224
        return l.channel.State().LocalCommitment.CommitFee
933✔
2225
}
2226

2227
// exceedsFeeExposureLimit returns whether or not the new proposed fee-rate
2228
// increases the total dust and fees within the channel past the configured
2229
// fee threshold. It first calculates the dust sum over every update in the
2230
// update log with the proposed fee-rate and taking into account both the local
2231
// and remote dust limits. It uses every update in the update log instead of
2232
// what is actually on the local and remote commitments because it is assumed
2233
// that in a worst-case scenario, every update in the update log could
2234
// theoretically be on either commitment transaction and this needs to be
2235
// accounted for with this fee-rate. It then calculates the local and remote
2236
// commitment fees given the proposed fee-rate. Finally, it tallies the results
2237
// and determines if the fee threshold has been exceeded.
2238
func (l *channelLink) exceedsFeeExposureLimit(
2239
        feePerKw chainfee.SatPerKWeight) (bool, error) {
6✔
2240

6✔
2241
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
6✔
2242

6✔
2243
        // Get the sum of dust for both the local and remote commitments using
6✔
2244
        // this "dry-run" fee.
6✔
2245
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
6✔
2246
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
6✔
2247

6✔
2248
        // Calculate the local and remote commitment fees using this dry-run
6✔
2249
        // fee.
6✔
2250
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
2251
        if err != nil {
6✔
2252
                return false, err
×
2253
        }
×
2254

2255
        // Finally, check whether the max fee exposure was exceeded on either
2256
        // future commitment transaction with the fee-rate.
2257
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
6✔
2258
        if totalLocalDust > l.cfg.MaxFeeExposure {
6✔
2259
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
2260
                        "local dust: %v, local fee: %v", l.ShortChanID(),
×
2261
                        totalLocalDust, localFee)
×
2262

×
2263
                return true, nil
×
2264
        }
×
2265

2266
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
6✔
2267
                remoteFee,
6✔
2268
        )
6✔
2269

6✔
2270
        if totalRemoteDust > l.cfg.MaxFeeExposure {
6✔
2271
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
2272
                        "remote dust: %v, remote fee: %v", l.ShortChanID(),
×
2273
                        totalRemoteDust, remoteFee)
×
2274

×
2275
                return true, nil
×
2276
        }
×
2277

2278
        return false, nil
6✔
2279
}
2280

2281
// isOverexposedWithHtlc calculates whether the proposed HTLC will make the
2282
// channel exceed the fee threshold. It first fetches the largest fee-rate that
2283
// may be on any unrevoked commitment transaction. Then, using this fee-rate,
2284
// determines if the to-be-added HTLC is dust. If the HTLC is dust, it adds to
2285
// the overall dust sum. If it is not dust, it contributes to weight, which
2286
// also adds to the overall dust sum by an increase in fees. If the dust sum on
2287
// either commitment exceeds the configured fee threshold, this function
2288
// returns true.
2289
func (l *channelLink) isOverexposedWithHtlc(htlc *lnwire.UpdateAddHTLC,
2290
        incoming bool) bool {
933✔
2291

933✔
2292
        dustClosure := l.getDustClosure()
933✔
2293

933✔
2294
        feeRate := l.channel.WorstCaseFeeRate()
933✔
2295

933✔
2296
        amount := htlc.Amount.ToSatoshis()
933✔
2297

933✔
2298
        // See if this HTLC is dust on both the local and remote commitments.
933✔
2299
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
933✔
2300
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
933✔
2301

933✔
2302
        // Calculate the dust sum for the local and remote commitments.
933✔
2303
        localDustSum := l.getDustSum(
933✔
2304
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
933✔
2305
        )
933✔
2306
        remoteDustSum := l.getDustSum(
933✔
2307
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
933✔
2308
        )
933✔
2309

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

933✔
2313
        if l.getCommitFee(true) > commitFee {
968✔
2314
                commitFee = l.getCommitFee(true)
35✔
2315
        }
35✔
2316

2317
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
933✔
2318

933✔
2319
        localDustSum += commitFeeMSat
933✔
2320
        remoteDustSum += commitFeeMSat
933✔
2321

933✔
2322
        // Calculate the additional fee increase if this is a non-dust HTLC.
933✔
2323
        weight := lntypes.WeightUnit(input.HTLCWeight)
933✔
2324
        additional := lnwire.NewMSatFromSatoshis(
933✔
2325
                feeRate.FeeForWeight(weight),
933✔
2326
        )
933✔
2327

933✔
2328
        if isLocalDust {
1,569✔
2329
                // If this is dust, it doesn't contribute to weight but does
636✔
2330
                // contribute to the overall dust sum.
636✔
2331
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
636✔
2332
        } else {
936✔
2333
                // Account for the fee increase that comes with an increase in
300✔
2334
                // weight.
300✔
2335
                localDustSum += additional
300✔
2336
        }
300✔
2337

2338
        if localDustSum > l.cfg.MaxFeeExposure {
937✔
2339
                // The max fee exposure was exceeded.
4✔
2340
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
4✔
2341
                        "overexposed, total local dust: %v (current commit "+
4✔
2342
                        "fee: %v)", l.ShortChanID(), htlc, localDustSum)
4✔
2343

4✔
2344
                return true
4✔
2345
        }
4✔
2346

2347
        if isRemoteDust {
1,562✔
2348
                // If this is dust, it doesn't contribute to weight but does
633✔
2349
                // contribute to the overall dust sum.
633✔
2350
                remoteDustSum += lnwire.NewMSatFromSatoshis(amount)
633✔
2351
        } else {
932✔
2352
                // Account for the fee increase that comes with an increase in
299✔
2353
                // weight.
299✔
2354
                remoteDustSum += additional
299✔
2355
        }
299✔
2356

2357
        if remoteDustSum > l.cfg.MaxFeeExposure {
929✔
2358
                // The max fee exposure was exceeded.
×
2359
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
2360
                        "overexposed, total remote dust: %v (current commit "+
×
2361
                        "fee: %v)", l.ShortChanID(), htlc, remoteDustSum)
×
2362

×
2363
                return true
×
2364
        }
×
2365

2366
        return false
929✔
2367
}
2368

2369
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
2370
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
2371
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
2372
// whether to evaluate on the local or remote commit, and finally an HTLC
2373
// amount to test.
2374
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
2375
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
2376

2377
// dustHelper is used to construct the dustClosure.
2378
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
2379
        remoteDustLimit btcutil.Amount) dustClosure {
1,802✔
2380

1,802✔
2381
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
1,802✔
2382
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
12,115✔
2383

10,313✔
2384
                var dustLimit btcutil.Amount
10,313✔
2385
                if whoseCommit.IsLocal() {
15,471✔
2386
                        dustLimit = localDustLimit
5,158✔
2387
                } else {
10,316✔
2388
                        dustLimit = remoteDustLimit
5,158✔
2389
                }
5,158✔
2390

2391
                return lnwallet.HtlcIsDust(
10,313✔
2392
                        chantype, incoming, whoseCommit, feerate, amt,
10,313✔
2393
                        dustLimit,
10,313✔
2394
                )
10,313✔
2395
        }
2396

2397
        return isDust
1,802✔
2398
}
2399

2400
// zeroConfConfirmed returns whether or not the zero-conf channel has
2401
// confirmed on-chain.
2402
//
2403
// Part of the scidAliasHandler interface.
2404
func (l *channelLink) zeroConfConfirmed() bool {
6✔
2405
        return l.channel.State().ZeroConfConfirmed()
6✔
2406
}
6✔
2407

2408
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
2409
// should not be called for non-zero-conf channels.
2410
//
2411
// Part of the scidAliasHandler interface.
2412
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
6✔
2413
        return l.channel.State().ZeroConfRealScid()
6✔
2414
}
6✔
2415

2416
// isZeroConf returns whether or not the underlying channel is a zero-conf
2417
// channel.
2418
//
2419
// Part of the scidAliasHandler interface.
2420
func (l *channelLink) isZeroConf() bool {
216✔
2421
        return l.channel.State().IsZeroConf()
216✔
2422
}
216✔
2423

2424
// negotiatedAliasFeature returns whether or not the underlying channel has
2425
// negotiated the option-scid-alias feature bit. This will be true for both
2426
// option-scid-alias and zero-conf channel-types. It will also be true for
2427
// channels with the feature bit but without the above channel-types.
2428
//
2429
// Part of the scidAliasFeature interface.
2430
func (l *channelLink) negotiatedAliasFeature() bool {
377✔
2431
        return l.channel.State().NegotiatedAliasFeature()
377✔
2432
}
377✔
2433

2434
// getAliases returns the set of aliases for the underlying channel.
2435
//
2436
// Part of the scidAliasHandler interface.
2437
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
222✔
2438
        return l.cfg.GetAliases(l.ShortChanID())
222✔
2439
}
222✔
2440

2441
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
2442
//
2443
// Part of the scidAliasHandler interface.
2444
func (l *channelLink) attachFailAliasUpdate(closure func(
2445
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
217✔
2446

217✔
2447
        l.Lock()
217✔
2448
        l.cfg.FailAliasUpdate = closure
217✔
2449
        l.Unlock()
217✔
2450
}
217✔
2451

2452
// AttachMailBox updates the current mailbox used by this link, and hooks up
2453
// the mailbox's message and packet outboxes to the link's upstream and
2454
// downstream chans, respectively.
2455
func (l *channelLink) AttachMailBox(mailbox MailBox) {
216✔
2456
        l.Lock()
216✔
2457
        l.mailBox = mailbox
216✔
2458
        l.upstream = mailbox.MessageOutBox()
216✔
2459
        l.downstream = mailbox.PacketOutBox()
216✔
2460
        l.Unlock()
216✔
2461

216✔
2462
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
216✔
2463
        // never committed.
216✔
2464
        l.mailBox.SetFeeRate(l.getFeeRate())
216✔
2465

216✔
2466
        // Also set the mailbox's dust closure so that it can query whether HTLC's
216✔
2467
        // are dust given the current feerate.
216✔
2468
        l.mailBox.SetDustClosure(l.getDustClosure())
216✔
2469
}
216✔
2470

2471
// UpdateForwardingPolicy updates the forwarding policy for the target
2472
// ChannelLink. Once updated, the link will use the new forwarding policy to
2473
// govern if it an incoming HTLC should be forwarded or not. We assume that
2474
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
2475
// update all of the link's FwrdingPolicy's values.
2476
//
2477
// NOTE: Part of the ChannelLink interface.
2478
func (l *channelLink) UpdateForwardingPolicy(
2479
        newPolicy models.ForwardingPolicy) {
15✔
2480

15✔
2481
        l.Lock()
15✔
2482
        defer l.Unlock()
15✔
2483

15✔
2484
        l.cfg.FwrdingPolicy = newPolicy
15✔
2485
}
15✔
2486

2487
// CheckHtlcForward should return a nil error if the passed HTLC details
2488
// satisfy the current forwarding policy fo the target link. Otherwise,
2489
// a LinkError with a valid protocol failure message should be returned
2490
// in order to signal to the source of the HTLC, the policy consistency
2491
// issue.
2492
//
2493
// NOTE: Part of the ChannelLink interface.
2494
func (l *channelLink) CheckHtlcForward(payHash [32]byte, incomingHtlcAmt,
2495
        amtToForward lnwire.MilliSatoshi, incomingTimeout,
2496
        outgoingTimeout uint32, inboundFee models.InboundFee,
2497
        heightNow uint32, originalScid lnwire.ShortChannelID,
2498
        customRecords lnwire.CustomRecords) *LinkError {
52✔
2499

52✔
2500
        l.RLock()
52✔
2501
        policy := l.cfg.FwrdingPolicy
52✔
2502
        l.RUnlock()
52✔
2503

52✔
2504
        // Using the outgoing HTLC amount, we'll calculate the outgoing
52✔
2505
        // fee this incoming HTLC must carry in order to satisfy the constraints
52✔
2506
        // of the outgoing link.
52✔
2507
        outFee := ExpectedFee(policy, amtToForward)
52✔
2508

52✔
2509
        // Then calculate the inbound fee that we charge based on the sum of
52✔
2510
        // outgoing HTLC amount and outgoing fee.
52✔
2511
        inFee := inboundFee.CalcFee(amtToForward + outFee)
52✔
2512

52✔
2513
        // Add up both fee components. It is important to calculate both fees
52✔
2514
        // separately. An alternative way of calculating is to first determine
52✔
2515
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
52✔
2516
        // rounding may cause the result to be slightly higher than in the case
52✔
2517
        // of separately rounded fee components. This potentially causes failed
52✔
2518
        // forwards for senders and is something to be avoided.
52✔
2519
        expectedFee := inFee + int64(outFee)
52✔
2520

52✔
2521
        // If the actual fee is less than our expected fee, then we'll reject
52✔
2522
        // this HTLC as it didn't provide a sufficient amount of fees, or the
52✔
2523
        // values have been tampered with, or the send used incorrect/dated
52✔
2524
        // information to construct the forwarding information for this hop. In
52✔
2525
        // any case, we'll cancel this HTLC.
52✔
2526
        actualFee := int64(incomingHtlcAmt) - int64(amtToForward)
52✔
2527
        if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
61✔
2528
                l.log.Warnf("outgoing htlc(%x) has insufficient fee: "+
9✔
2529
                        "expected %v, got %v: incoming=%v, outgoing=%v, "+
9✔
2530
                        "inboundFee=%v",
9✔
2531
                        payHash[:], expectedFee, actualFee,
9✔
2532
                        incomingHtlcAmt, amtToForward, inboundFee,
9✔
2533
                )
9✔
2534

9✔
2535
                // As part of the returned error, we'll send our latest routing
9✔
2536
                // policy so the sending node obtains the most up to date data.
9✔
2537
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
18✔
2538
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
9✔
2539
                }
9✔
2540
                failure := l.createFailureWithUpdate(false, originalScid, cb)
9✔
2541
                return NewLinkError(failure)
9✔
2542
        }
2543

2544
        // Check whether the outgoing htlc satisfies the channel policy.
2545
        err := l.canSendHtlc(
46✔
2546
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
46✔
2547
                originalScid, customRecords,
46✔
2548
        )
46✔
2549
        if err != nil {
62✔
2550
                return err
16✔
2551
        }
16✔
2552

2553
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
2554
        // the following constraint: the incoming time-lock minus our time-lock
2555
        // delta should equal the outgoing time lock. Otherwise, whether the
2556
        // sender messed up, or an intermediate node tampered with the HTLC.
2557
        timeDelta := policy.TimeLockDelta
33✔
2558
        if incomingTimeout < outgoingTimeout+timeDelta {
35✔
2559
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
2✔
2560
                        "expected at least %v block delta, got %v block delta",
2✔
2561
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
2✔
2562

2✔
2563
                // Grab the latest routing policy so the sending node is up to
2✔
2564
                // date with our current policy.
2✔
2565
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
2566
                        return lnwire.NewIncorrectCltvExpiry(
2✔
2567
                                incomingTimeout, *upd,
2✔
2568
                        )
2✔
2569
                }
2✔
2570
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
2571
                return NewLinkError(failure)
2✔
2572
        }
2573

2574
        return nil
31✔
2575
}
2576

2577
// CheckHtlcTransit should return a nil error if the passed HTLC details
2578
// satisfy the current channel policy.  Otherwise, a LinkError with a
2579
// valid protocol failure message should be returned in order to signal
2580
// the violation. This call is intended to be used for locally initiated
2581
// payments for which there is no corresponding incoming htlc.
2582
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
2583
        amt lnwire.MilliSatoshi, timeout uint32, heightNow uint32,
2584
        customRecords lnwire.CustomRecords) *LinkError {
409✔
2585

409✔
2586
        l.RLock()
409✔
2587
        policy := l.cfg.FwrdingPolicy
409✔
2588
        l.RUnlock()
409✔
2589

409✔
2590
        // We pass in hop.Source here as this is only used in the Switch when
409✔
2591
        // trying to send over a local link. This causes the fallback mechanism
409✔
2592
        // to occur.
409✔
2593
        return l.canSendHtlc(
409✔
2594
                policy, payHash, amt, timeout, heightNow, hop.Source,
409✔
2595
                customRecords,
409✔
2596
        )
409✔
2597
}
409✔
2598

2599
// canSendHtlc checks whether the given htlc parameters satisfy
2600
// the channel's amount and time lock constraints.
2601
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
2602
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
2603
        heightNow uint32, originalScid lnwire.ShortChannelID,
2604
        customRecords lnwire.CustomRecords) *LinkError {
452✔
2605

452✔
2606
        // Validate HTLC amount against policy limits.
452✔
2607
        linkErr := l.validateHtlcAmount(
452✔
2608
                policy, payHash, amt, originalScid, customRecords,
452✔
2609
        )
452✔
2610
        if linkErr != nil {
466✔
2611
                return linkErr
14✔
2612
        }
14✔
2613

2614
        // We want to avoid offering an HTLC which will expire in the near
2615
        // future, so we'll reject an HTLC if the outgoing expiration time is
2616
        // too close to the current height.
2617
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
443✔
2618
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
2✔
2619
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
2✔
2620
                        timeout, heightNow)
2✔
2621

2✔
2622
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
2623
                        return lnwire.NewExpiryTooSoon(*upd)
2✔
2624
                }
2✔
2625
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
2626

2✔
2627
                return NewLinkError(failure)
2✔
2628
        }
2629

2630
        // Check absolute max delta.
2631
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
440✔
2632
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
1✔
2633
                        "the future: got %v, but maximum is %v", payHash[:],
1✔
2634
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
1✔
2635

1✔
2636
                return NewLinkError(&lnwire.FailExpiryTooFar{})
1✔
2637
        }
1✔
2638

2639
        // We now check the available bandwidth to see if this HTLC can be
2640
        // forwarded.
2641
        availableBandwidth := l.Bandwidth()
438✔
2642

438✔
2643
        auxBandwidth, externalErr := fn.MapOptionZ(
438✔
2644
                l.cfg.AuxTrafficShaper,
438✔
2645
                func(ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
438✔
2646
                        var htlcBlob fn.Option[tlv.Blob]
×
2647
                        blob, err := customRecords.Serialize()
×
2648
                        if err != nil {
×
2649
                                return fn.Err[OptionalBandwidth](
×
2650
                                        fmt.Errorf("unable to serialize "+
×
2651
                                                "custom records: %w", err))
×
2652
                        }
×
2653

2654
                        if len(blob) > 0 {
×
2655
                                htlcBlob = fn.Some(blob)
×
2656
                        }
×
2657

2658
                        return l.AuxBandwidth(amt, originalScid, htlcBlob, ts)
×
2659
                },
2660
        ).Unpack()
2661
        if externalErr != nil {
438✔
2662
                l.log.Errorf("Unable to determine aux bandwidth: %v",
×
2663
                        externalErr)
×
2664

×
2665
                return NewLinkError(&lnwire.FailTemporaryNodeFailure{})
×
2666
        }
×
2667

2668
        if auxBandwidth.IsHandled && auxBandwidth.Bandwidth.IsSome() {
438✔
2669
                auxBandwidth.Bandwidth.WhenSome(
×
2670
                        func(bandwidth lnwire.MilliSatoshi) {
×
2671
                                availableBandwidth = bandwidth
×
2672
                        },
×
2673
                )
2674
        }
2675

2676
        // Check to see if there is enough balance in this channel.
2677
        if amt > availableBandwidth {
442✔
2678
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
4✔
2679
                        "larger than %v", amt, availableBandwidth)
4✔
2680
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
2681
                        return lnwire.NewTemporaryChannelFailure(upd)
4✔
2682
                }
4✔
2683
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
2684

4✔
2685
                return NewDetailedLinkError(
4✔
2686
                        failure, OutgoingFailureInsufficientBalance,
4✔
2687
                )
4✔
2688
        }
2689

2690
        return nil
437✔
2691
}
2692

2693
// AuxBandwidth returns the bandwidth that can be used for a channel, expressed
2694
// in milli-satoshi. This might be different from the regular BTC bandwidth for
2695
// custom channels. This will always return fn.None() for a regular (non-custom)
2696
// channel.
2697
func (l *channelLink) AuxBandwidth(amount lnwire.MilliSatoshi,
2698
        cid lnwire.ShortChannelID, htlcBlob fn.Option[tlv.Blob],
2699
        ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
×
2700

×
2701
        fundingBlob := l.FundingCustomBlob()
×
2702
        shouldHandle, err := ts.ShouldHandleTraffic(cid, fundingBlob, htlcBlob)
×
2703
        if err != nil {
×
2704
                return fn.Err[OptionalBandwidth](fmt.Errorf("traffic shaper "+
×
2705
                        "failed to decide whether to handle traffic: %w", err))
×
2706
        }
×
2707

2708
        log.Debugf("ShortChannelID=%v: aux traffic shaper is handling "+
×
2709
                "traffic: %v", cid, shouldHandle)
×
2710

×
2711
        // If this channel isn't handled by the aux traffic shaper, we'll return
×
2712
        // early.
×
2713
        if !shouldHandle {
×
2714
                return fn.Ok(OptionalBandwidth{
×
2715
                        IsHandled: false,
×
2716
                })
×
2717
        }
×
2718

2719
        peerBytes := l.cfg.Peer.PubKey()
×
2720

×
2721
        peer, err := route.NewVertexFromBytes(peerBytes[:])
×
2722
        if err != nil {
×
2723
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to decode "+
×
2724
                        "peer pub key: %v", err))
×
2725
        }
×
2726

2727
        // Ask for a specific bandwidth to be used for the channel.
2728
        commitmentBlob := l.CommitmentCustomBlob()
×
2729
        auxBandwidth, err := ts.PaymentBandwidth(
×
2730
                fundingBlob, htlcBlob, commitmentBlob, l.Bandwidth(), amount,
×
2731
                l.channel.FetchLatestAuxHTLCView(), peer,
×
2732
        )
×
2733
        if err != nil {
×
2734
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to get "+
×
2735
                        "bandwidth from external traffic shaper: %w", err))
×
2736
        }
×
2737

2738
        log.Debugf("ShortChannelID=%v: aux traffic shaper reported available "+
×
2739
                "bandwidth: %v", cid, auxBandwidth)
×
2740

×
2741
        return fn.Ok(OptionalBandwidth{
×
2742
                IsHandled: true,
×
2743
                Bandwidth: fn.Some(auxBandwidth),
×
2744
        })
×
2745
}
2746

2747
// Stats returns the statistics of channel link.
2748
//
2749
// NOTE: Part of the ChannelLink interface.
2750
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
7✔
2751
        snapshot := l.channel.StateSnapshot()
7✔
2752

7✔
2753
        return snapshot.ChannelCommitment.CommitHeight,
7✔
2754
                snapshot.TotalMSatSent,
7✔
2755
                snapshot.TotalMSatReceived
7✔
2756
}
7✔
2757

2758
// String returns the string representation of channel link.
2759
//
2760
// NOTE: Part of the ChannelLink interface.
2761
func (l *channelLink) String() string {
×
2762
        return l.channel.ChannelPoint().String()
×
2763
}
×
2764

2765
// handleSwitchPacket handles the switch packets. This packets which might be
2766
// forwarded to us from another channel link in case the htlc update came from
2767
// another peer or if the update was created by user
2768
//
2769
// NOTE: Part of the packetHandler interface.
2770
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
482✔
2771
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
482✔
2772
                pkt.inKey(), pkt.outKey())
482✔
2773

482✔
2774
        return l.mailBox.AddPacket(pkt)
482✔
2775
}
482✔
2776

2777
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
2778
// to us from remote peer we have a channel with.
2779
//
2780
// NOTE: Part of the ChannelLink interface.
2781
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
3,372✔
2782
        select {
3,372✔
2783
        case <-l.cg.Done():
×
2784
                // Return early if the link is already in the process of
×
2785
                // quitting. It doesn't make sense to hand the message to the
×
2786
                // mailbox here.
×
2787
                return
×
2788
        default:
3,372✔
2789
        }
2790

2791
        err := l.mailBox.AddMessage(message)
3,372✔
2792
        if err != nil {
3,372✔
2793
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
2794
        }
×
2795
}
2796

2797
// updateChannelFee updates the commitment fee-per-kw on this channel by
2798
// committing to an update_fee message.
2799
func (l *channelLink) updateChannelFee(ctx context.Context,
2800
        feePerKw chainfee.SatPerKWeight) error {
3✔
2801

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

3✔
2804
        // We skip sending the UpdateFee message if the channel is not
3✔
2805
        // currently eligible to forward messages.
3✔
2806
        if !l.eligibleToUpdate() {
3✔
2807
                l.log.Debugf("skipping fee update for inactive channel")
×
2808
                return nil
×
2809
        }
×
2810

2811
        // Check and see if our proposed fee-rate would make us exceed the fee
2812
        // threshold.
2813
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
3✔
2814
        if err != nil {
3✔
2815
                // This shouldn't typically happen. If it does, it indicates
×
2816
                // something is wrong with our channel state.
×
2817
                return err
×
2818
        }
×
2819

2820
        if thresholdExceeded {
3✔
2821
                return fmt.Errorf("link fee threshold exceeded")
×
2822
        }
×
2823

2824
        // First, we'll update the local fee on our commitment.
2825
        if err := l.channel.UpdateFee(feePerKw); err != nil {
3✔
2826
                return err
×
2827
        }
×
2828

2829
        // The fee passed the channel's validation checks, so we update the
2830
        // mailbox feerate.
2831
        l.mailBox.SetFeeRate(feePerKw)
3✔
2832

3✔
2833
        // We'll then attempt to send a new UpdateFee message, and also lock it
3✔
2834
        // in immediately by triggering a commitment update.
3✔
2835
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
3✔
2836
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
2837
                return err
×
2838
        }
×
2839

2840
        return l.updateCommitTx(ctx)
3✔
2841
}
2842

2843
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
2844
// after receiving a revocation from the remote party, and reprocesses them in
2845
// the context of the provided forwarding package. Any settles or fails that
2846
// have already been acknowledged in the forwarding package will not be sent to
2847
// the switch.
2848
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
1,194✔
2849
        if len(fwdPkg.SettleFails) == 0 {
2,072✔
2850
                l.log.Trace("fwd package has no settle/fails to process " +
878✔
2851
                        "exiting early")
878✔
2852

878✔
2853
                return
878✔
2854
        }
878✔
2855

2856
        // Exit early if the fwdPkg is already processed.
2857
        if fwdPkg.State == channeldb.FwdStateCompleted {
319✔
2858
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
2859

×
2860
                return
×
2861
        }
×
2862

2863
        l.log.Debugf("settle-fail-filter: %v", fwdPkg.SettleFailFilter)
319✔
2864

319✔
2865
        var switchPackets []*htlcPacket
319✔
2866
        for i, update := range fwdPkg.SettleFails {
638✔
2867
                destRef := fwdPkg.DestRef(uint16(i))
319✔
2868

319✔
2869
                // Skip any settles or fails that have already been
319✔
2870
                // acknowledged by the incoming link that originated the
319✔
2871
                // forwarded Add.
319✔
2872
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
319✔
2873
                        continue
×
2874
                }
2875

2876
                // TODO(roasbeef): rework log entries to a shared
2877
                // interface.
2878

2879
                switch msg := update.UpdateMsg.(type) {
319✔
2880
                // A settle for an HTLC we previously forwarded HTLC has been
2881
                // received. So we'll forward the HTLC to the switch which will
2882
                // handle propagating the settle to the prior hop.
2883
                case *lnwire.UpdateFulfillHTLC:
196✔
2884
                        // If hodl.SettleIncoming is requested, we will not
196✔
2885
                        // forward the SETTLE to the switch and will not signal
196✔
2886
                        // a free slot on the commitment transaction.
196✔
2887
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
196✔
2888
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
2889
                                continue
×
2890
                        }
2891

2892
                        settlePacket := &htlcPacket{
196✔
2893
                                outgoingChanID: l.ShortChanID(),
196✔
2894
                                outgoingHTLCID: msg.ID,
196✔
2895
                                destRef:        &destRef,
196✔
2896
                                htlc:           msg,
196✔
2897
                        }
196✔
2898

196✔
2899
                        // Add the packet to the batch to be forwarded, and
196✔
2900
                        // notify the overflow queue that a spare spot has been
196✔
2901
                        // freed up within the commitment state.
196✔
2902
                        switchPackets = append(switchPackets, settlePacket)
196✔
2903

2904
                // A failureCode message for a previously forwarded HTLC has
2905
                // been received. As a result a new slot will be freed up in
2906
                // our commitment state, so we'll forward this to the switch so
2907
                // the backwards undo can continue.
2908
                case *lnwire.UpdateFailHTLC:
126✔
2909
                        // If hodl.SettleIncoming is requested, we will not
126✔
2910
                        // forward the FAIL to the switch and will not signal a
126✔
2911
                        // free slot on the commitment transaction.
126✔
2912
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
126✔
2913
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
2914
                                continue
×
2915
                        }
2916

2917
                        // Fetch the reason the HTLC was canceled so we can
2918
                        // continue to propagate it. This failure originated
2919
                        // from another node, so the linkFailure field is not
2920
                        // set on the packet.
2921
                        failPacket := &htlcPacket{
126✔
2922
                                outgoingChanID: l.ShortChanID(),
126✔
2923
                                outgoingHTLCID: msg.ID,
126✔
2924
                                destRef:        &destRef,
126✔
2925
                                htlc:           msg,
126✔
2926
                        }
126✔
2927

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

126✔
2930
                        // If the failure message lacks an HMAC (but includes
126✔
2931
                        // the 4 bytes for encoding the message and padding
126✔
2932
                        // lengths, then this means that we received it as an
126✔
2933
                        // UpdateFailMalformedHTLC. As a result, we'll signal
126✔
2934
                        // that we need to convert this error within the switch
126✔
2935
                        // to an actual error, by encrypting it as if we were
126✔
2936
                        // the originating hop.
126✔
2937
                        convertedErrorSize := lnwire.FailureMessageLength + 4
126✔
2938
                        if len(msg.Reason) == convertedErrorSize {
132✔
2939
                                failPacket.convertedError = true
6✔
2940
                        }
6✔
2941

2942
                        // Add the packet to the batch to be forwarded, and
2943
                        // notify the overflow queue that a spare spot has been
2944
                        // freed up within the commitment state.
2945
                        switchPackets = append(switchPackets, failPacket)
126✔
2946
                }
2947
        }
2948

2949
        // Only spawn the task forward packets we have a non-zero number.
2950
        if len(switchPackets) > 0 {
638✔
2951
                go l.forwardBatch(false, switchPackets...)
319✔
2952
        }
319✔
2953
}
2954

2955
// processRemoteAdds serially processes each of the Add payment descriptors
2956
// which have been "locked-in" by receiving a revocation from the remote party.
2957
// The forwarding package provided instructs how to process this batch,
2958
// indicating whether this is the first time these Adds are being processed, or
2959
// whether we are reprocessing as a result of a failure or restart. Adds that
2960
// have already been acknowledged in the forwarding package will be ignored.
2961
//
2962
// NOTE: This function needs also be called for fwd packages with no ADDs
2963
// because it marks the fwdPkg as processed by writing the FwdFilter into the
2964
// database.
2965
//
2966
//nolint:funlen
2967
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
1,196✔
2968
        // Exit early if the fwdPkg is already processed.
1,196✔
2969
        if fwdPkg.State == channeldb.FwdStateCompleted {
1,196✔
2970
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
2971

×
2972
                return
×
2973
        }
×
2974

2975
        l.log.Tracef("processing %d remote adds for height %d",
1,196✔
2976
                len(fwdPkg.Adds), fwdPkg.Height)
1,196✔
2977

1,196✔
2978
        // decodeReqs is a list of requests sent to the onion decoder. We expect
1,196✔
2979
        // the same length of responses to be returned.
1,196✔
2980
        decodeReqs := make([]hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds))
1,196✔
2981

1,196✔
2982
        // unackedAdds is a list of ADDs that's waiting for the remote's
1,196✔
2983
        // settle/fail update.
1,196✔
2984
        unackedAdds := make([]*lnwire.UpdateAddHTLC, 0, len(fwdPkg.Adds))
1,196✔
2985

1,196✔
2986
        for i, update := range fwdPkg.Adds {
1,648✔
2987
                // If this index is already found in the ack filter, the
452✔
2988
                // response to this forwarding decision has already been
452✔
2989
                // committed by one of our commitment txns. ADDs in this state
452✔
2990
                // are waiting for the rest of the fwding package to get acked
452✔
2991
                // before being garbage collected.
452✔
2992
                if fwdPkg.State == channeldb.FwdStateProcessed &&
452✔
2993
                        fwdPkg.AckFilter.Contains(uint16(i)) {
452✔
2994

×
2995
                        continue
×
2996
                }
2997

2998
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
904✔
2999
                        // Before adding the new htlc to the state machine,
452✔
3000
                        // parse the onion object in order to obtain the
452✔
3001
                        // routing information with DecodeHopIterator function
452✔
3002
                        // which process the Sphinx packet.
452✔
3003
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
452✔
3004

452✔
3005
                        req := hop.DecodeHopIteratorRequest{
452✔
3006
                                OnionReader:    onionReader,
452✔
3007
                                RHash:          msg.PaymentHash[:],
452✔
3008
                                IncomingCltv:   msg.Expiry,
452✔
3009
                                IncomingAmount: msg.Amount,
452✔
3010
                                BlindingPoint:  msg.BlindingPoint,
452✔
3011
                        }
452✔
3012

452✔
3013
                        decodeReqs = append(decodeReqs, req)
452✔
3014
                        unackedAdds = append(unackedAdds, msg)
452✔
3015
                }
452✔
3016
        }
3017

3018
        // If the fwdPkg has already been processed, it means we are
3019
        // reforwarding the packets again, which happens only on a restart.
3020
        reforward := fwdPkg.State == channeldb.FwdStateProcessed
1,196✔
3021

1,196✔
3022
        // Atomically decode the incoming htlcs, simultaneously checking for
1,196✔
3023
        // replay attempts. A particular index in the returned, spare list of
1,196✔
3024
        // channel iterators should only be used if the failure code at the
1,196✔
3025
        // same index is lnwire.FailCodeNone.
1,196✔
3026
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
1,196✔
3027
                fwdPkg.ID(), decodeReqs, reforward,
1,196✔
3028
        )
1,196✔
3029
        if sphinxErr != nil {
1,196✔
3030
                l.failf(LinkFailureError{code: ErrInternalError},
×
3031
                        "unable to decode hop iterators: %v", sphinxErr)
×
3032
                return
×
3033
        }
×
3034

3035
        var switchPackets []*htlcPacket
1,196✔
3036

1,196✔
3037
        for i, update := range unackedAdds {
1,648✔
3038
                idx := uint16(i)
452✔
3039
                sourceRef := fwdPkg.SourceRef(idx)
452✔
3040
                add := *update
452✔
3041

452✔
3042
                // An incoming HTLC add has been full-locked in. As a result we
452✔
3043
                // can now examine the forwarding details of the HTLC, and the
452✔
3044
                // HTLC itself to decide if: we should forward it, cancel it,
452✔
3045
                // or are able to settle it (and it adheres to our fee related
452✔
3046
                // constraints).
452✔
3047

452✔
3048
                // Before adding the new htlc to the state machine, parse the
452✔
3049
                // onion object in order to obtain the routing information with
452✔
3050
                // DecodeHopIterator function which process the Sphinx packet.
452✔
3051
                chanIterator, failureCode := decodeResps[i].Result()
452✔
3052
                if failureCode != lnwire.CodeNone {
457✔
3053
                        // If we're unable to process the onion blob then we
5✔
3054
                        // should send the malformed htlc error to payment
5✔
3055
                        // sender.
5✔
3056
                        l.sendMalformedHTLCError(
5✔
3057
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
5✔
3058
                        )
5✔
3059

5✔
3060
                        l.log.Errorf("unable to decode onion hop iterator "+
5✔
3061
                                "for htlc(id=%v, hash=%x): %v", add.ID,
5✔
3062
                                add.PaymentHash, failureCode)
5✔
3063

5✔
3064
                        continue
5✔
3065
                }
3066

3067
                heightNow := l.cfg.BestHeight()
450✔
3068

450✔
3069
                pld, routeRole, pldErr := chanIterator.HopPayload()
450✔
3070
                if pldErr != nil {
453✔
3071
                        // If we're unable to process the onion payload, or we
3✔
3072
                        // received invalid onion payload failure, then we
3✔
3073
                        // should send an error back to the caller so the HTLC
3✔
3074
                        // can be canceled.
3✔
3075
                        var failedType uint64
3✔
3076

3✔
3077
                        // We need to get the underlying error value, so we
3✔
3078
                        // can't use errors.As as suggested by the linter.
3✔
3079
                        //nolint:errorlint
3✔
3080
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
3✔
3081
                                failedType = uint64(e.Type)
×
3082
                        }
×
3083

3084
                        // If we couldn't parse the payload, make our best
3085
                        // effort at creating an error encrypter that knows
3086
                        // what blinding type we were, but if we couldn't
3087
                        // parse the payload we have no way of knowing whether
3088
                        // we were the introduction node or not.
3089
                        //
3090
                        //nolint:ll
3091
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
3✔
3092
                                l.cfg.ExtractErrorEncrypter,
3✔
3093
                                // We need our route role here because we
3✔
3094
                                // couldn't parse or validate the payload.
3✔
3095
                                routeRole == hop.RouteRoleIntroduction,
3✔
3096
                        )
3✔
3097
                        if failCode != lnwire.CodeNone {
3✔
3098
                                l.log.Errorf("could not extract error "+
×
3099
                                        "encrypter: %v", pldErr)
×
3100

×
3101
                                // We can't process this htlc, send back
×
3102
                                // malformed.
×
3103
                                l.sendMalformedHTLCError(
×
3104
                                        add.ID, failureCode, add.OnionBlob,
×
3105
                                        &sourceRef,
×
3106
                                )
×
3107

×
3108
                                continue
×
3109
                        }
3110

3111
                        // TODO: currently none of the test unit infrastructure
3112
                        // is setup to handle TLV payloads, so testing this
3113
                        // would require implementing a separate mock iterator
3114
                        // for TLV payloads that also supports injecting invalid
3115
                        // payloads. Deferring this non-trival effort till a
3116
                        // later date
3117
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
3✔
3118

3✔
3119
                        l.sendHTLCError(
3✔
3120
                                add, sourceRef, NewLinkError(failure),
3✔
3121
                                obfuscator, false,
3✔
3122
                        )
3✔
3123

3✔
3124
                        l.log.Errorf("unable to decode forwarding "+
3✔
3125
                                "instructions: %v", pldErr)
3✔
3126

3✔
3127
                        continue
3✔
3128
                }
3129

3130
                // Retrieve onion obfuscator from onion blob in order to
3131
                // produce initial obfuscation of the onion failureCode.
3132
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
450✔
3133
                        l.cfg.ExtractErrorEncrypter,
450✔
3134
                        routeRole == hop.RouteRoleIntroduction,
450✔
3135
                )
450✔
3136
                if failureCode != lnwire.CodeNone {
451✔
3137
                        // If we're unable to process the onion blob than we
1✔
3138
                        // should send the malformed htlc error to payment
1✔
3139
                        // sender.
1✔
3140
                        l.sendMalformedHTLCError(
1✔
3141
                                add.ID, failureCode, add.OnionBlob,
1✔
3142
                                &sourceRef,
1✔
3143
                        )
1✔
3144

1✔
3145
                        l.log.Errorf("unable to decode onion "+
1✔
3146
                                "obfuscator: %v", failureCode)
1✔
3147

1✔
3148
                        continue
1✔
3149
                }
3150

3151
                fwdInfo := pld.ForwardingInfo()
449✔
3152

449✔
3153
                // Check whether the payload we've just processed uses our
449✔
3154
                // node as the introduction point (gave us a blinding key in
449✔
3155
                // the payload itself) and fail it back if we don't support
449✔
3156
                // route blinding.
449✔
3157
                if fwdInfo.NextBlinding.IsSome() &&
449✔
3158
                        l.cfg.DisallowRouteBlinding {
452✔
3159

3✔
3160
                        failure := lnwire.NewInvalidBlinding(
3✔
3161
                                fn.Some(add.OnionBlob),
3✔
3162
                        )
3✔
3163

3✔
3164
                        l.sendHTLCError(
3✔
3165
                                add, sourceRef, NewLinkError(failure),
3✔
3166
                                obfuscator, false,
3✔
3167
                        )
3✔
3168

3✔
3169
                        l.log.Error("rejected htlc that uses use as an " +
3✔
3170
                                "introduction point when we do not support " +
3✔
3171
                                "route blinding")
3✔
3172

3✔
3173
                        continue
3✔
3174
                }
3175

3176
                switch fwdInfo.NextHop {
449✔
3177
                case hop.Exit:
413✔
3178
                        err := l.processExitHop(
413✔
3179
                                add, sourceRef, obfuscator, fwdInfo,
413✔
3180
                                heightNow, pld,
413✔
3181
                        )
413✔
3182
                        if err != nil {
413✔
3183
                                l.failf(LinkFailureError{
×
3184
                                        code: ErrInternalError,
×
3185
                                }, "%v", err)
×
3186

×
3187
                                return
×
3188
                        }
×
3189

3190
                // There are additional channels left within this route. So
3191
                // we'll simply do some forwarding package book-keeping.
3192
                default:
39✔
3193
                        // If hodl.AddIncoming is requested, we will not
39✔
3194
                        // validate the forwarded ADD, nor will we send the
39✔
3195
                        // packet to the htlc switch.
39✔
3196
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
39✔
3197
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3198
                                continue
×
3199
                        }
3200

3201
                        endorseValue := l.experimentalEndorsement(
39✔
3202
                                record.CustomSet(add.CustomRecords),
39✔
3203
                        )
39✔
3204
                        endorseType := uint64(
39✔
3205
                                lnwire.ExperimentalEndorsementType,
39✔
3206
                        )
39✔
3207

39✔
3208
                        switch fwdPkg.State {
39✔
3209
                        case channeldb.FwdStateProcessed:
3✔
3210
                                // This add was not forwarded on the previous
3✔
3211
                                // processing phase, run it through our
3✔
3212
                                // validation pipeline to reproduce an error.
3✔
3213
                                // This may trigger a different error due to
3✔
3214
                                // expiring timelocks, but we expect that an
3✔
3215
                                // error will be reproduced.
3✔
3216
                                if !fwdPkg.FwdFilter.Contains(idx) {
3✔
3217
                                        break
×
3218
                                }
3219

3220
                                // Otherwise, it was already processed, we can
3221
                                // can collect it and continue.
3222
                                outgoingAdd := &lnwire.UpdateAddHTLC{
3✔
3223
                                        Expiry:        fwdInfo.OutgoingCTLV,
3✔
3224
                                        Amount:        fwdInfo.AmountToForward,
3✔
3225
                                        PaymentHash:   add.PaymentHash,
3✔
3226
                                        BlindingPoint: fwdInfo.NextBlinding,
3✔
3227
                                }
3✔
3228

3✔
3229
                                endorseValue.WhenSome(func(e byte) {
6✔
3230
                                        custRecords := map[uint64][]byte{
3✔
3231
                                                endorseType: {e},
3✔
3232
                                        }
3✔
3233

3✔
3234
                                        outgoingAdd.CustomRecords = custRecords
3✔
3235
                                })
3✔
3236

3237
                                // Finally, we'll encode the onion packet for
3238
                                // the _next_ hop using the hop iterator
3239
                                // decoded for the current hop.
3240
                                buf := bytes.NewBuffer(
3✔
3241
                                        outgoingAdd.OnionBlob[0:0],
3✔
3242
                                )
3✔
3243

3✔
3244
                                // We know this cannot fail, as this ADD
3✔
3245
                                // was marked forwarded in a previous
3✔
3246
                                // round of processing.
3✔
3247
                                chanIterator.EncodeNextHop(buf)
3✔
3248

3✔
3249
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
3250

3✔
3251
                                //nolint:ll
3✔
3252
                                updatePacket := &htlcPacket{
3✔
3253
                                        incomingChanID:       l.ShortChanID(),
3✔
3254
                                        incomingHTLCID:       add.ID,
3✔
3255
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
3256
                                        sourceRef:            &sourceRef,
3✔
3257
                                        incomingAmount:       add.Amount,
3✔
3258
                                        amount:               outgoingAdd.Amount,
3✔
3259
                                        htlc:                 outgoingAdd,
3✔
3260
                                        obfuscator:           obfuscator,
3✔
3261
                                        incomingTimeout:      add.Expiry,
3✔
3262
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
3263
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
3264
                                        inboundFee:           inboundFee,
3✔
3265
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
3266
                                }
3✔
3267
                                switchPackets = append(
3✔
3268
                                        switchPackets, updatePacket,
3✔
3269
                                )
3✔
3270

3✔
3271
                                continue
3✔
3272
                        }
3273

3274
                        // TODO(roasbeef): ensure don't accept outrageous
3275
                        // timeout for htlc
3276

3277
                        // With all our forwarding constraints met, we'll
3278
                        // create the outgoing HTLC using the parameters as
3279
                        // specified in the forwarding info.
3280
                        addMsg := &lnwire.UpdateAddHTLC{
39✔
3281
                                Expiry:        fwdInfo.OutgoingCTLV,
39✔
3282
                                Amount:        fwdInfo.AmountToForward,
39✔
3283
                                PaymentHash:   add.PaymentHash,
39✔
3284
                                BlindingPoint: fwdInfo.NextBlinding,
39✔
3285
                        }
39✔
3286

39✔
3287
                        endorseValue.WhenSome(func(e byte) {
78✔
3288
                                addMsg.CustomRecords = map[uint64][]byte{
39✔
3289
                                        endorseType: {e},
39✔
3290
                                }
39✔
3291
                        })
39✔
3292

3293
                        // Finally, we'll encode the onion packet for the
3294
                        // _next_ hop using the hop iterator decoded for the
3295
                        // current hop.
3296
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
39✔
3297
                        err := chanIterator.EncodeNextHop(buf)
39✔
3298
                        if err != nil {
39✔
3299
                                l.log.Errorf("unable to encode the "+
×
3300
                                        "remaining route %v", err)
×
3301

×
3302
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
3303
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
3304
                                }
×
3305

3306
                                failure := l.createFailureWithUpdate(
×
3307
                                        true, hop.Source, cb,
×
3308
                                )
×
3309

×
3310
                                l.sendHTLCError(
×
3311
                                        add, sourceRef, NewLinkError(failure),
×
3312
                                        obfuscator, false,
×
3313
                                )
×
3314
                                continue
×
3315
                        }
3316

3317
                        // Now that this add has been reprocessed, only append
3318
                        // it to our list of packets to forward to the switch
3319
                        // this is the first time processing the add. If the
3320
                        // fwd pkg has already been processed, then we entered
3321
                        // the above section to recreate a previous error.  If
3322
                        // the packet had previously been forwarded, it would
3323
                        // have been added to switchPackets at the top of this
3324
                        // section.
3325
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
78✔
3326
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
39✔
3327

39✔
3328
                                //nolint:ll
39✔
3329
                                updatePacket := &htlcPacket{
39✔
3330
                                        incomingChanID:       l.ShortChanID(),
39✔
3331
                                        incomingHTLCID:       add.ID,
39✔
3332
                                        outgoingChanID:       fwdInfo.NextHop,
39✔
3333
                                        sourceRef:            &sourceRef,
39✔
3334
                                        incomingAmount:       add.Amount,
39✔
3335
                                        amount:               addMsg.Amount,
39✔
3336
                                        htlc:                 addMsg,
39✔
3337
                                        obfuscator:           obfuscator,
39✔
3338
                                        incomingTimeout:      add.Expiry,
39✔
3339
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
39✔
3340
                                        inOnionCustomRecords: pld.CustomRecords(),
39✔
3341
                                        inboundFee:           inboundFee,
39✔
3342
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
39✔
3343
                                }
39✔
3344

39✔
3345
                                fwdPkg.FwdFilter.Set(idx)
39✔
3346
                                switchPackets = append(switchPackets,
39✔
3347
                                        updatePacket)
39✔
3348
                        }
39✔
3349
                }
3350
        }
3351

3352
        // Commit the htlcs we are intending to forward if this package has not
3353
        // been fully processed.
3354
        if fwdPkg.State == channeldb.FwdStateLockedIn {
2,389✔
3355
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
1,193✔
3356
                if err != nil {
1,193✔
3357
                        l.failf(LinkFailureError{code: ErrInternalError},
×
3358
                                "unable to set fwd filter: %v", err)
×
3359
                        return
×
3360
                }
×
3361
        }
3362

3363
        if len(switchPackets) == 0 {
2,356✔
3364
                return
1,160✔
3365
        }
1,160✔
3366

3367
        l.log.Debugf("forwarding %d packets to switch: reforward=%v",
39✔
3368
                len(switchPackets), reforward)
39✔
3369

39✔
3370
        // NOTE: This call is made synchronous so that we ensure all circuits
39✔
3371
        // are committed in the exact order that they are processed in the link.
39✔
3372
        // Failing to do this could cause reorderings/gaps in the range of
39✔
3373
        // opened circuits, which violates assumptions made by the circuit
39✔
3374
        // trimming.
39✔
3375
        l.forwardBatch(reforward, switchPackets...)
39✔
3376
}
3377

3378
// experimentalEndorsement returns the value to set for our outgoing
3379
// experimental endorsement field, and a boolean indicating whether it should
3380
// be populated on the outgoing htlc.
3381
func (l *channelLink) experimentalEndorsement(
3382
        customUpdateAdd record.CustomSet) fn.Option[byte] {
39✔
3383

39✔
3384
        // Only relay experimental signal if we are within the experiment
39✔
3385
        // period.
39✔
3386
        if !l.cfg.ShouldFwdExpEndorsement() {
42✔
3387
                return fn.None[byte]()
3✔
3388
        }
3✔
3389

3390
        // If we don't have any custom records or the experimental field is
3391
        // not set, just forward a zero value.
3392
        if len(customUpdateAdd) == 0 {
78✔
3393
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
39✔
3394
        }
39✔
3395

3396
        t := uint64(lnwire.ExperimentalEndorsementType)
3✔
3397
        value, set := customUpdateAdd[t]
3✔
3398
        if !set {
3✔
3399
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
3400
        }
×
3401

3402
        // We expect at least one byte for this field, consider it invalid if
3403
        // it has no data and just forward a zero value.
3404
        if len(value) == 0 {
3✔
3405
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
3406
        }
×
3407

3408
        // Only forward endorsed if the incoming link is endorsed.
3409
        if value[0] == lnwire.ExperimentalEndorsed {
6✔
3410
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
3✔
3411
        }
3✔
3412

3413
        // Forward as unendorsed otherwise, including cases where we've
3414
        // received an invalid value that uses more than 3 bits of information.
3415
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
3416
}
3417

3418
// processExitHop handles an htlc for which this link is the exit hop. It
3419
// returns a boolean indicating whether the commitment tx needs an update.
3420
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
3421
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
3422
        fwdInfo hop.ForwardingInfo, heightNow uint32,
3423
        payload invoices.Payload) error {
413✔
3424

413✔
3425
        // If hodl.ExitSettle is requested, we will not validate the final hop's
413✔
3426
        // ADD, nor will we settle the corresponding invoice or respond with the
413✔
3427
        // preimage.
413✔
3428
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
523✔
3429
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
110✔
3430
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
110✔
3431

110✔
3432
                return nil
110✔
3433
        }
110✔
3434

3435
        // In case the traffic shaper is active, we'll check if the HTLC has
3436
        // custom records and skip the amount check in the onion payload below.
3437
        isCustomHTLC := fn.MapOptionZ(
306✔
3438
                l.cfg.AuxTrafficShaper,
306✔
3439
                func(ts AuxTrafficShaper) bool {
306✔
3440
                        return ts.IsCustomHTLC(add.CustomRecords)
×
3441
                },
×
3442
        )
3443

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

100✔
3453
                failure := NewLinkError(
100✔
3454
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
100✔
3455
                )
100✔
3456
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
100✔
3457

100✔
3458
                return nil
100✔
3459
        }
100✔
3460

3461
        // We'll also ensure that our time-lock value has been computed
3462
        // correctly.
3463
        if add.Expiry < fwdInfo.OutgoingCTLV {
207✔
3464
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
1✔
3465
                        "incompatible time-lock: expected <=%v, got %v",
1✔
3466
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
1✔
3467

1✔
3468
                failure := NewLinkError(
1✔
3469
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
1✔
3470
                )
1✔
3471

1✔
3472
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
1✔
3473

1✔
3474
                return nil
1✔
3475
        }
1✔
3476

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

205✔
3482
        circuitKey := models.CircuitKey{
205✔
3483
                ChanID: l.ShortChanID(),
205✔
3484
                HtlcID: add.ID,
205✔
3485
        }
205✔
3486

205✔
3487
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
205✔
3488
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
205✔
3489
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
205✔
3490
        )
205✔
3491
        if err != nil {
205✔
3492
                return err
×
3493
        }
×
3494

3495
        // Create a hodlHtlc struct and decide either resolved now or later.
3496
        htlc := hodlHtlc{
205✔
3497
                add:        add,
205✔
3498
                sourceRef:  sourceRef,
205✔
3499
                obfuscator: obfuscator,
205✔
3500
        }
205✔
3501

205✔
3502
        // If the event is nil, the invoice is being held, so we save payment
205✔
3503
        // descriptor for future reference.
205✔
3504
        if event == nil {
264✔
3505
                l.hodlMap[circuitKey] = htlc
59✔
3506
                return nil
59✔
3507
        }
59✔
3508

3509
        // Process the received resolution.
3510
        return l.processHtlcResolution(event, htlc)
149✔
3511
}
3512

3513
// settleHTLC settles the HTLC on the channel.
3514
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
3515
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
200✔
3516

200✔
3517
        hash := preimage.Hash()
200✔
3518

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

200✔
3521
        err := l.channel.SettleHTLC(
200✔
3522
                preimage, htlcIndex, &sourceRef, nil, nil,
200✔
3523
        )
200✔
3524
        if err != nil {
200✔
3525
                return fmt.Errorf("unable to settle htlc: %w", err)
×
3526
        }
×
3527

3528
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
3529
        // fake one before sending it to the peer.
3530
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
203✔
3531
                l.log.Warnf(hodl.BogusSettle.Warning())
3✔
3532
                preimage = [32]byte{}
3✔
3533
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
3✔
3534
        }
3✔
3535

3536
        // HTLC was successfully settled locally send notification about it
3537
        // remote peer.
3538
        err = l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
200✔
3539
                ChanID:          l.ChanID(),
200✔
3540
                ID:              htlcIndex,
200✔
3541
                PaymentPreimage: preimage,
200✔
3542
        })
200✔
3543
        if err != nil {
200✔
3544
                l.log.Errorf("failed to send UpdateFulfillHTLC: %v", err)
×
3545
        }
×
3546

3547
        // Once we have successfully settled the htlc, notify a settle event.
3548
        l.cfg.HtlcNotifier.NotifySettleEvent(
200✔
3549
                HtlcKey{
200✔
3550
                        IncomingCircuit: models.CircuitKey{
200✔
3551
                                ChanID: l.ShortChanID(),
200✔
3552
                                HtlcID: htlcIndex,
200✔
3553
                        },
200✔
3554
                },
200✔
3555
                preimage,
200✔
3556
                HtlcEventTypeReceive,
200✔
3557
        )
200✔
3558

200✔
3559
        return nil
200✔
3560
}
3561

3562
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
3563
// err chan for the individual responses. This method is intended to be spawned
3564
// as a goroutine so the responses can be handled in the background.
3565
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
580✔
3566
        // Don't forward packets for which we already have a response in our
580✔
3567
        // mailbox. This could happen if a packet fails and is buffered in the
580✔
3568
        // mailbox, and the incoming link flaps.
580✔
3569
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
580✔
3570
        for _, pkt := range packets {
1,160✔
3571
                if l.mailBox.HasPacket(pkt.inKey()) {
583✔
3572
                        continue
3✔
3573
                }
3574

3575
                filteredPkts = append(filteredPkts, pkt)
580✔
3576
        }
3577

3578
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
580✔
3579
        if err != nil {
591✔
3580
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
3581
                        "settle/fail over htlcswitch: %v", err)
11✔
3582
        }
11✔
3583
}
3584

3585
// sendHTLCError functions cancels HTLC and send cancel message back to the
3586
// peer from which HTLC was received.
3587
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
3588
        sourceRef channeldb.AddRef, failure *LinkError,
3589
        e hop.ErrorEncrypter, isReceive bool) {
108✔
3590

108✔
3591
        reason, err := e.EncryptFirstHop(failure.WireMessage())
108✔
3592
        if err != nil {
108✔
3593
                l.log.Errorf("unable to obfuscate error: %v", err)
×
3594
                return
×
3595
        }
×
3596

3597
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
108✔
3598
        if err != nil {
108✔
3599
                l.log.Errorf("unable cancel htlc: %v", err)
×
3600
                return
×
3601
        }
×
3602

3603
        // Send the appropriate failure message depending on whether we're
3604
        // in a blinded route or not.
3605
        if err := l.sendIncomingHTLCFailureMsg(
108✔
3606
                add.ID, e, reason,
108✔
3607
        ); err != nil {
108✔
3608
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
3609
                return
×
3610
        }
×
3611

3612
        // Notify a link failure on our incoming link. Outgoing htlc information
3613
        // is not available at this point, because we have not decrypted the
3614
        // onion, so it is excluded.
3615
        var eventType HtlcEventType
108✔
3616
        if isReceive {
216✔
3617
                eventType = HtlcEventTypeReceive
108✔
3618
        } else {
111✔
3619
                eventType = HtlcEventTypeForward
3✔
3620
        }
3✔
3621

3622
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
108✔
3623
                HtlcKey{
108✔
3624
                        IncomingCircuit: models.CircuitKey{
108✔
3625
                                ChanID: l.ShortChanID(),
108✔
3626
                                HtlcID: add.ID,
108✔
3627
                        },
108✔
3628
                },
108✔
3629
                HtlcInfo{
108✔
3630
                        IncomingTimeLock: add.Expiry,
108✔
3631
                        IncomingAmt:      add.Amount,
108✔
3632
                },
108✔
3633
                eventType,
108✔
3634
                failure,
108✔
3635
                true,
108✔
3636
        )
108✔
3637
}
3638

3639
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
3640
// peer from which the HTLC was received. This function is primarily used to
3641
// handle the special requirements of route blinding, specifically:
3642
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
3643
// - Introduction nodes should return regular HTLC failure messages.
3644
//
3645
// It accepts the original opaque failure, which will be used in the case
3646
// that we're not part of a blinded route and an error encrypter that'll be
3647
// used if we are the introduction node and need to present an error as if
3648
// we're the failing party.
3649
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
3650
        e hop.ErrorEncrypter,
3651
        originalFailure lnwire.OpaqueReason) error {
124✔
3652

124✔
3653
        var msg lnwire.Message
124✔
3654
        switch {
124✔
3655
        // Our circuit's error encrypter will be nil if this was a locally
3656
        // initiated payment. We can only hit a blinded error for a locally
3657
        // initiated payment if we allow ourselves to be picked as the
3658
        // introduction node for our own payments and in that case we
3659
        // shouldn't reach this code. To prevent the HTLC getting stuck,
3660
        // we fail it back and log an error.
3661
        // code.
3662
        case e == nil:
×
3663
                msg = &lnwire.UpdateFailHTLC{
×
3664
                        ChanID: l.ChanID(),
×
3665
                        ID:     htlcIndex,
×
3666
                        Reason: originalFailure,
×
3667
                }
×
3668

×
3669
                l.log.Errorf("Unexpected blinded failure when "+
×
3670
                        "we are the sending node, incoming htlc: %v(%v)",
×
3671
                        l.ShortChanID(), htlcIndex)
×
3672

3673
        // For cleartext hops (ie, non-blinded/normal) we don't need any
3674
        // transformation on the error message and can just send the original.
3675
        case !e.Type().IsBlinded():
124✔
3676
                msg = &lnwire.UpdateFailHTLC{
124✔
3677
                        ChanID: l.ChanID(),
124✔
3678
                        ID:     htlcIndex,
124✔
3679
                        Reason: originalFailure,
124✔
3680
                }
124✔
3681

3682
        // When we're the introduction node, we need to convert the error to
3683
        // a UpdateFailHTLC.
3684
        case e.Type() == hop.EncrypterTypeIntroduction:
3✔
3685
                l.log.Debugf("Introduction blinded node switching out failure "+
3✔
3686
                        "error: %v", htlcIndex)
3✔
3687

3✔
3688
                // The specification does not require that we set the onion
3✔
3689
                // blob.
3✔
3690
                failureMsg := lnwire.NewInvalidBlinding(
3✔
3691
                        fn.None[[lnwire.OnionPacketSize]byte](),
3✔
3692
                )
3✔
3693
                reason, err := e.EncryptFirstHop(failureMsg)
3✔
3694
                if err != nil {
3✔
3695
                        return err
×
3696
                }
×
3697

3698
                msg = &lnwire.UpdateFailHTLC{
3✔
3699
                        ChanID: l.ChanID(),
3✔
3700
                        ID:     htlcIndex,
3✔
3701
                        Reason: reason,
3✔
3702
                }
3✔
3703

3704
        // If we are a relaying node, we need to switch out any error that
3705
        // we've received to a malformed HTLC error.
3706
        case e.Type() == hop.EncrypterTypeRelaying:
3✔
3707
                l.log.Debugf("Relaying blinded node switching out malformed "+
3✔
3708
                        "error: %v", htlcIndex)
3✔
3709

3✔
3710
                msg = &lnwire.UpdateFailMalformedHTLC{
3✔
3711
                        ChanID:      l.ChanID(),
3✔
3712
                        ID:          htlcIndex,
3✔
3713
                        FailureCode: lnwire.CodeInvalidBlinding,
3✔
3714
                }
3✔
3715

3716
        default:
×
3717
                return fmt.Errorf("unexpected encrypter: %d", e)
×
3718
        }
3719

3720
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
124✔
3721
                l.log.Warnf("Send update fail failed: %v", err)
×
3722
        }
×
3723

3724
        return nil
124✔
3725
}
3726

3727
// sendMalformedHTLCError helper function which sends the malformed HTLC update
3728
// to the payment sender.
3729
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
3730
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
3731
        sourceRef *channeldb.AddRef) {
6✔
3732

6✔
3733
        shaOnionBlob := sha256.Sum256(onionBlob[:])
6✔
3734
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
6✔
3735
        if err != nil {
6✔
3736
                l.log.Errorf("unable cancel htlc: %v", err)
×
3737
                return
×
3738
        }
×
3739

3740
        err = l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
6✔
3741
                ChanID:       l.ChanID(),
6✔
3742
                ID:           htlcIndex,
6✔
3743
                ShaOnionBlob: shaOnionBlob,
6✔
3744
                FailureCode:  code,
6✔
3745
        })
6✔
3746
        if err != nil {
6✔
3747
                l.log.Errorf("failed to send UpdateFailMalformedHTLC: %v", err)
×
3748
        }
×
3749
}
3750

3751
// failf is a function which is used to encapsulate the action necessary for
3752
// properly failing the link. It takes a LinkFailureError, which will be passed
3753
// to the OnChannelFailure closure, in order for it to determine if we should
3754
// force close the channel, and if we should send an error message to the
3755
// remote peer.
3756
func (l *channelLink) failf(linkErr LinkFailureError, format string,
3757
        a ...interface{}) {
18✔
3758

18✔
3759
        reason := fmt.Errorf(format, a...)
18✔
3760

18✔
3761
        // Return if we have already notified about a failure.
18✔
3762
        if l.failed {
21✔
3763
                l.log.Warnf("ignoring link failure (%v), as link already "+
3✔
3764
                        "failed", reason)
3✔
3765
                return
3✔
3766
        }
3✔
3767

3768
        l.log.Errorf("failing link: %s with error: %v", reason, linkErr)
18✔
3769

18✔
3770
        // Set failed, such that we won't process any more updates, and notify
18✔
3771
        // the peer about the failure.
18✔
3772
        l.failed = true
18✔
3773
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
18✔
3774
}
3775

3776
// FundingCustomBlob returns the custom funding blob of the channel that this
3777
// link is associated with. The funding blob represents static information about
3778
// the channel that was created at channel funding time.
3779
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
3780
        if l.channel == nil {
×
3781
                return fn.None[tlv.Blob]()
×
3782
        }
×
3783

3784
        if l.channel.State() == nil {
×
3785
                return fn.None[tlv.Blob]()
×
3786
        }
×
3787

3788
        return l.channel.State().CustomBlob
×
3789
}
3790

3791
// CommitmentCustomBlob returns the custom blob of the current local commitment
3792
// of the channel that this link is associated with.
3793
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
3794
        if l.channel == nil {
×
3795
                return fn.None[tlv.Blob]()
×
3796
        }
×
3797

3798
        return l.channel.LocalCommitmentBlob()
×
3799
}
3800

3801
// handleHtlcResolution takes an HTLC resolution and processes it by draining
3802
// the hodlQueue. Once processed, a commit_sig is sent to the remote to update
3803
// their commitment.
3804
func (l *channelLink) handleHtlcResolution(ctx context.Context,
3805
        hodlItem any) error {
58✔
3806

58✔
3807
        htlcResolution, ok := hodlItem.(invoices.HtlcResolution)
58✔
3808
        if !ok {
58✔
3809
                return fmt.Errorf("expect HtlcResolution, got %T", hodlItem)
×
3810
        }
×
3811

3812
        err := l.processHodlQueue(ctx, htlcResolution)
58✔
3813
        // No error, success.
58✔
3814
        if err == nil {
115✔
3815
                return nil
57✔
3816
        }
57✔
3817

3818
        switch {
1✔
3819
        // If the duplicate keystone error was encountered, fail back
3820
        // gracefully.
3821
        case errors.Is(err, ErrDuplicateKeystone):
×
3822
                l.failf(
×
3823
                        LinkFailureError{
×
3824
                                code: ErrCircuitError,
×
3825
                        },
×
3826
                        "process hodl queue: temporary circuit error: %v", err,
×
3827
                )
×
3828

3829
        // Send an Error message to the peer.
3830
        default:
1✔
3831
                l.failf(
1✔
3832
                        LinkFailureError{
1✔
3833
                                code: ErrInternalError,
1✔
3834
                        },
1✔
3835
                        "process hodl queue: unable to update commitment: %v",
1✔
3836
                        err,
1✔
3837
                )
1✔
3838
        }
3839

3840
        return err
1✔
3841
}
3842

3843
// handleQuiescenceReq takes a locally initialized (RPC) quiescence request and
3844
// forwards it to the quiescer for further processing.
3845
func (l *channelLink) handleQuiescenceReq(req StfuReq) error {
4✔
3846
        l.quiescer.InitStfu(req)
4✔
3847

4✔
3848
        if !l.noDanglingUpdates(lntypes.Local) {
4✔
3849
                return nil
×
3850
        }
×
3851

3852
        err := l.quiescer.SendOwedStfu()
4✔
3853
        if err != nil {
4✔
3854
                l.stfuFailf("SendOwedStfu: %v", err)
×
3855
                res := fn.Err[lntypes.ChannelParty](err)
×
3856
                req.Resolve(res)
×
3857
        }
×
3858

3859
        return err
4✔
3860
}
3861

3862
// handleUpdateFee is called whenever the `updateFeeTimer` ticks. It is used to
3863
// decide whether we should send an `update_fee` msg to update the commitment's
3864
// feerate.
3865
func (l *channelLink) handleUpdateFee(ctx context.Context) error {
4✔
3866
        // If we're not the initiator of the channel, we don't control the fees,
4✔
3867
        // so we can ignore this.
4✔
3868
        if !l.channel.IsInitiator() {
4✔
3869
                return nil
×
3870
        }
×
3871

3872
        // If we are the initiator, then we'll sample the current fee rate to
3873
        // get into the chain within 3 blocks.
3874
        netFee, err := l.sampleNetworkFee()
4✔
3875
        if err != nil {
4✔
3876
                return fmt.Errorf("unable to sample network fee: %w", err)
×
3877
        }
×
3878

3879
        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
4✔
3880

4✔
3881
        newCommitFee := l.channel.IdealCommitFeeRate(
4✔
3882
                netFee, minRelayFee,
4✔
3883
                l.cfg.MaxAnchorsCommitFeeRate,
4✔
3884
                l.cfg.MaxFeeAllocation,
4✔
3885
        )
4✔
3886

4✔
3887
        // We determine if we should adjust the commitment fee based on the
4✔
3888
        // current commitment fee, the suggested new commitment fee and the
4✔
3889
        // current minimum relay fee rate.
4✔
3890
        commitFee := l.channel.CommitFeeRate()
4✔
3891
        if !shouldAdjustCommitFee(newCommitFee, commitFee, minRelayFee) {
5✔
3892
                return nil
1✔
3893
        }
1✔
3894

3895
        // If we do, then we'll send a new UpdateFee message to the remote
3896
        // party, to be locked in with a new update.
3897
        err = l.updateChannelFee(ctx, newCommitFee)
3✔
3898
        if err != nil {
3✔
3899
                return fmt.Errorf("unable to update fee rate: %w", err)
×
3900
        }
×
3901

3902
        return nil
3✔
3903
}
3904

3905
// toggleBatchTicker checks whether we need to resume or pause the batch ticker.
3906
// When we have no pending updates, the ticker is paused, otherwise resumed.
3907
func (l *channelLink) toggleBatchTicker() {
4,184✔
3908
        // If the previous event resulted in a non-empty batch, resume the batch
4,184✔
3909
        // ticker so that it can be cleared. Otherwise pause the ticker to
4,184✔
3910
        // prevent waking up the htlcManager while the batch is empty.
4,184✔
3911
        numUpdates := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
4,184✔
3912
        if numUpdates > 0 {
4,693✔
3913
                l.cfg.BatchTicker.Resume()
509✔
3914
                l.log.Tracef("BatchTicker resumed, NumPendingUpdates(Local, "+
509✔
3915
                        "Remote)=%d", numUpdates)
509✔
3916

509✔
3917
                return
509✔
3918
        }
509✔
3919

3920
        l.cfg.BatchTicker.Pause()
3,678✔
3921
        l.log.Trace("BatchTicker paused due to zero NumPendingUpdates" +
3,678✔
3922
                "(Local, Remote)")
3,678✔
3923
}
3924

3925
// resumeLink is called when starting a previous link. It will go through the
3926
// reestablishment protocol and reforwarding packets that are yet resolved.
3927
func (l *channelLink) resumeLink(ctx context.Context) error {
216✔
3928
        // If this isn't the first time that this channel link has been created,
216✔
3929
        // then we'll need to check to see if we need to re-synchronize state
216✔
3930
        // with the remote peer. settledHtlcs is a map of HTLC's that we
216✔
3931
        // re-settled as part of the channel state sync.
216✔
3932
        if l.cfg.SyncStates {
389✔
3933
                err := l.syncChanStates(ctx)
173✔
3934
                if err != nil {
176✔
3935
                        l.handleChanSyncErr(err)
3✔
3936

3✔
3937
                        return err
3✔
3938
                }
3✔
3939
        }
3940

3941
        // If a shutdown message has previously been sent on this link, then we
3942
        // need to make sure that we have disabled any HTLC adds on the outgoing
3943
        // direction of the link and that we re-resend the same shutdown message
3944
        // that we previously sent.
3945
        //
3946
        // TODO(yy): we should either move this to chanCloser, or move all
3947
        // shutdown handling logic to be managed by the link, but not a mixed of
3948
        // partial management by two subsystems.
3949
        l.cfg.PreviouslySentShutdown.WhenSome(func(shutdown lnwire.Shutdown) {
219✔
3950
                // Immediately disallow any new outgoing HTLCs.
3✔
3951
                if !l.DisableAdds(Outgoing) {
3✔
3952
                        l.log.Warnf("Outgoing link adds already disabled")
×
3953
                }
×
3954

3955
                // Re-send the shutdown message the peer. Since syncChanStates
3956
                // would have sent any outstanding CommitSig, it is fine for us
3957
                // to immediately queue the shutdown message now.
3958
                err := l.cfg.Peer.SendMessage(false, &shutdown)
3✔
3959
                if err != nil {
3✔
3960
                        l.log.Warnf("Error sending shutdown message: %v", err)
×
3961
                }
×
3962
        })
3963

3964
        // We've successfully reestablished the channel, mark it as such to
3965
        // allow the switch to forward HTLCs in the outbound direction.
3966
        l.markReestablished()
216✔
3967

216✔
3968
        // With the channel states synced, we now reset the mailbox to ensure we
216✔
3969
        // start processing all unacked packets in order. This is done here to
216✔
3970
        // ensure that all acknowledgments that occur during channel
216✔
3971
        // resynchronization have taken affect, causing us only to pull unacked
216✔
3972
        // packets after starting to read from the downstream mailbox.
216✔
3973
        err := l.mailBox.ResetPackets()
216✔
3974
        if err != nil {
216✔
3975
                l.log.Errorf("failed to reset packets: %v", err)
×
3976
        }
×
3977

3978
        // If the channel is pending, there's no need to reforwarding packets.
3979
        if l.ShortChanID() == hop.Source {
216✔
3980
                return nil
×
3981
        }
×
3982

3983
        // After cleaning up any memory pertaining to incoming packets, we now
3984
        // replay our forwarding packages to handle any htlcs that can be
3985
        // processed locally, or need to be forwarded out to the switch. We will
3986
        // only attempt to resolve packages if our short chan id indicates that
3987
        // the channel is not pending, otherwise we should have no htlcs to
3988
        // reforward.
3989
        err = l.resolveFwdPkgs(ctx)
216✔
3990
        switch {
216✔
3991
        // No error was encountered, success.
3992
        case err == nil:
215✔
3993
                // With our link's in-memory state fully reconstructed, spawn a
215✔
3994
                // goroutine to manage the reclamation of disk space occupied by
215✔
3995
                // completed forwarding packages.
215✔
3996
                l.cg.WgAdd(1)
215✔
3997
                go l.fwdPkgGarbager()
215✔
3998

215✔
3999
                return nil
215✔
4000

4001
        // If the duplicate keystone error was encountered, we'll fail without
4002
        // sending an Error message to the peer.
4003
        case errors.Is(err, ErrDuplicateKeystone):
×
4004
                l.failf(LinkFailureError{code: ErrCircuitError},
×
4005
                        "temporary circuit error: %v", err)
×
4006

4007
        // A non-nil error was encountered, send an Error message to
4008
        // the peer.
4009
        default:
1✔
4010
                l.failf(LinkFailureError{code: ErrInternalError},
1✔
4011
                        "unable to resolve fwd pkgs: %v", err)
1✔
4012
        }
4013

4014
        return err
1✔
4015
}
4016

4017
// processRemoteUpdateAddHTLC takes an `UpdateAddHTLC` msg sent from the remote
4018
// and processes it.
4019
func (l *channelLink) processRemoteUpdateAddHTLC(
4020
        msg *lnwire.UpdateAddHTLC) error {
453✔
4021

453✔
4022
        if l.IsFlushing(Incoming) {
453✔
4023
                // This is forbidden by the protocol specification. The best
×
4024
                // chance we have to deal with this is to drop the connection.
×
4025
                // This should roll back the channel state to the last
×
4026
                // CommitSig. If the remote has already sent a CommitSig we
×
4027
                // haven't received yet, channel state will be re-synchronized
×
4028
                // with a ChannelReestablish message upon reconnection and the
×
4029
                // protocol state that caused us to flush the link will be
×
4030
                // rolled back. In the event that there was some
×
4031
                // non-deterministic behavior in the remote that caused them to
×
4032
                // violate the protocol, we have a decent shot at correcting it
×
4033
                // this way, since reconnecting will put us in the cleanest
×
4034
                // possible state to try again.
×
4035
                //
×
4036
                // In addition to the above, it is possible for us to hit this
×
4037
                // case in situations where we improperly handle message
×
4038
                // ordering due to concurrency choices. An issue has been filed
×
4039
                // to address this here:
×
4040
                // https://github.com/lightningnetwork/lnd/issues/8393
×
4041
                err := errors.New("received add while link is flushing")
×
4042
                l.failf(
×
4043
                        LinkFailureError{
×
4044
                                code:             ErrInvalidUpdate,
×
4045
                                FailureAction:    LinkFailureDisconnect,
×
4046
                                PermanentFailure: false,
×
4047
                                Warning:          true,
×
4048
                        }, "%v", err,
×
4049
                )
×
4050

×
4051
                return err
×
4052
        }
×
4053

4054
        // Disallow htlcs with blinding points set if we haven't enabled the
4055
        // feature. This saves us from having to process the onion at all, but
4056
        // will only catch blinded payments where we are a relaying node (as the
4057
        // blinding point will be in the payload when we're the introduction
4058
        // node).
4059
        if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
453✔
4060
                err := errors.New("blinding point included when route " +
×
4061
                        "blinding is disabled")
×
4062

×
4063
                l.failf(LinkFailureError{code: ErrInvalidUpdate}, "%v", err)
×
4064

×
4065
                return err
×
4066
        }
×
4067

4068
        // We have to check the limit here rather than later in the switch
4069
        // because the counterparty can keep sending HTLC's without sending a
4070
        // revoke. This would mean that the switch check would only occur later.
4071
        if l.isOverexposedWithHtlc(msg, true) {
453✔
4072
                err := errors.New("peer sent us an HTLC that exceeded our " +
×
4073
                        "max fee exposure")
×
4074
                l.failf(LinkFailureError{code: ErrInternalError}, "%v", err)
×
4075

×
4076
                return err
×
4077
        }
×
4078

4079
        // We just received an add request from an upstream peer, so we add it
4080
        // to our state machine, then add the HTLC to our "settle" list in the
4081
        // event that we know the preimage.
4082
        index, err := l.channel.ReceiveHTLC(msg)
453✔
4083
        if err != nil {
453✔
4084
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
4085
                        "unable to handle upstream add HTLC: %v", err)
×
4086

×
4087
                return err
×
4088
        }
×
4089

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

453✔
4093
        return nil
453✔
4094
}
4095

4096
// processRemoteUpdateFulfillHTLC takes an `UpdateFulfillHTLC` msg sent from the
4097
// remote and processes it.
4098
func (l *channelLink) processRemoteUpdateFulfillHTLC(
4099
        msg *lnwire.UpdateFulfillHTLC) error {
230✔
4100

230✔
4101
        pre := msg.PaymentPreimage
230✔
4102
        idx := msg.ID
230✔
4103

230✔
4104
        // Before we pipeline the settle, we'll check the set of active htlc's
230✔
4105
        // to see if the related UpdateAddHTLC has been fully locked-in.
230✔
4106
        var lockedin bool
230✔
4107
        htlcs := l.channel.ActiveHtlcs()
230✔
4108
        for _, add := range htlcs {
837✔
4109
                // The HTLC will be outgoing and match idx.
607✔
4110
                if !add.Incoming && add.HtlcIndex == idx {
835✔
4111
                        lockedin = true
228✔
4112
                        break
228✔
4113
                }
4114
        }
4115

4116
        if !lockedin {
232✔
4117
                err := errors.New("unable to handle upstream settle")
2✔
4118
                l.failf(LinkFailureError{code: ErrInvalidUpdate}, "%v", err)
2✔
4119

2✔
4120
                return err
2✔
4121
        }
2✔
4122

4123
        if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
231✔
4124
                l.failf(
3✔
4125
                        LinkFailureError{
3✔
4126
                                code:          ErrInvalidUpdate,
3✔
4127
                                FailureAction: LinkFailureForceClose,
3✔
4128
                        },
3✔
4129
                        "unable to handle upstream settle HTLC: %v", err,
3✔
4130
                )
3✔
4131

3✔
4132
                return err
3✔
4133
        }
3✔
4134

4135
        settlePacket := &htlcPacket{
228✔
4136
                outgoingChanID: l.ShortChanID(),
228✔
4137
                outgoingHTLCID: idx,
228✔
4138
                htlc: &lnwire.UpdateFulfillHTLC{
228✔
4139
                        PaymentPreimage: pre,
228✔
4140
                },
228✔
4141
        }
228✔
4142

228✔
4143
        // Add the newly discovered preimage to our growing list of uncommitted
228✔
4144
        // preimage. These will be written to the witness cache just before
228✔
4145
        // accepting the next commitment signature from the remote peer.
228✔
4146
        l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
228✔
4147

228✔
4148
        // Pipeline this settle, send it to the switch.
228✔
4149
        go l.forwardBatch(false, settlePacket)
228✔
4150

228✔
4151
        return nil
228✔
4152
}
4153

4154
// processRemoteUpdateFailMalformedHTLC takes an `UpdateFailMalformedHTLC` msg
4155
// sent from the remote and processes it.
4156
func (l *channelLink) processRemoteUpdateFailMalformedHTLC(
4157
        msg *lnwire.UpdateFailMalformedHTLC) error {
6✔
4158

6✔
4159
        // Convert the failure type encoded within the HTLC fail message to the
6✔
4160
        // proper generic lnwire error code.
6✔
4161
        var failure lnwire.FailureMessage
6✔
4162
        switch msg.FailureCode {
6✔
4163
        case lnwire.CodeInvalidOnionVersion:
4✔
4164
                failure = &lnwire.FailInvalidOnionVersion{
4✔
4165
                        OnionSHA256: msg.ShaOnionBlob,
4✔
4166
                }
4✔
4167
        case lnwire.CodeInvalidOnionHmac:
×
4168
                failure = &lnwire.FailInvalidOnionHmac{
×
4169
                        OnionSHA256: msg.ShaOnionBlob,
×
4170
                }
×
4171

4172
        case lnwire.CodeInvalidOnionKey:
×
4173
                failure = &lnwire.FailInvalidOnionKey{
×
4174
                        OnionSHA256: msg.ShaOnionBlob,
×
4175
                }
×
4176

4177
        // Handle malformed errors that are part of a blinded route. This case
4178
        // is slightly different, because we expect every relaying node in the
4179
        // blinded portion of the route to send malformed errors. If we're also
4180
        // a relaying node, we're likely going to switch this error out anyway
4181
        // for our own malformed error, but we handle the case here for
4182
        // completeness.
4183
        case lnwire.CodeInvalidBlinding:
3✔
4184
                failure = &lnwire.FailInvalidBlinding{
3✔
4185
                        OnionSHA256: msg.ShaOnionBlob,
3✔
4186
                }
3✔
4187

4188
        default:
2✔
4189
                l.log.Warnf("unexpected failure code received in "+
2✔
4190
                        "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
4191

2✔
4192
                // We don't just pass back the error we received from our
2✔
4193
                // successor. Otherwise we might report a failure that penalizes
2✔
4194
                // us more than needed. If the onion that we forwarded was
2✔
4195
                // correct, the node should have been able to send back its own
2✔
4196
                // failure. The node did not send back its own failure, so we
2✔
4197
                // assume there was a problem with the onion and report that
2✔
4198
                // back. We reuse the invalid onion key failure because there is
2✔
4199
                // no specific error for this case.
2✔
4200
                failure = &lnwire.FailInvalidOnionKey{
2✔
4201
                        OnionSHA256: msg.ShaOnionBlob,
2✔
4202
                }
2✔
4203
        }
4204

4205
        // With the error parsed, we'll convert the into it's opaque form.
4206
        var b bytes.Buffer
6✔
4207
        if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
6✔
4208
                return fmt.Errorf("unable to encode malformed error: %w", err)
×
4209
        }
×
4210

4211
        // If remote side have been unable to parse the onion blob we have sent
4212
        // to it, than we should transform the malformed HTLC message to the
4213
        // usual HTLC fail message.
4214
        err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
6✔
4215
        if err != nil {
6✔
4216
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
4217
                        "unable to handle upstream fail HTLC: %v", err)
×
4218

×
4219
                return err
×
4220
        }
×
4221

4222
        return nil
6✔
4223
}
4224

4225
// processRemoteUpdateFailHTLC takes an `UpdateFailHTLC` msg sent from the
4226
// remote and processes it.
4227
func (l *channelLink) processRemoteUpdateFailHTLC(
4228
        msg *lnwire.UpdateFailHTLC) error {
123✔
4229

123✔
4230
        // Verify that the failure reason is at least 256 bytes plus overhead.
123✔
4231
        const minimumFailReasonLength = lnwire.FailureMessageLength + 2 + 2 + 32
123✔
4232

123✔
4233
        if len(msg.Reason) < minimumFailReasonLength {
124✔
4234
                // We've received a reason with a non-compliant length. Older
1✔
4235
                // nodes happily relay back these failures that may originate
1✔
4236
                // from a node further downstream. Therefore we can't just fail
1✔
4237
                // the channel.
1✔
4238
                //
1✔
4239
                // We want to be compliant ourselves, so we also can't pass back
1✔
4240
                // the reason unmodified. And we must make sure that we don't
1✔
4241
                // hit the magic length check of 260 bytes in
1✔
4242
                // processRemoteSettleFails either.
1✔
4243
                //
1✔
4244
                // Because the reason is unreadable for the payer anyway, we
1✔
4245
                // just replace it by a compliant-length series of random bytes.
1✔
4246
                msg.Reason = make([]byte, minimumFailReasonLength)
1✔
4247
                _, err := crand.Read(msg.Reason[:])
1✔
4248
                if err != nil {
1✔
4249
                        return fmt.Errorf("random generation error: %w", err)
×
4250
                }
×
4251
        }
4252

4253
        // Add fail to the update log.
4254
        idx := msg.ID
123✔
4255
        err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
123✔
4256
        if err != nil {
123✔
4257
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
4258
                        "unable to handle upstream fail HTLC: %v", err)
×
4259

×
4260
                return err
×
4261
        }
×
4262

4263
        return nil
123✔
4264
}
4265

4266
// processRemoteCommitSig takes a `CommitSig` msg sent from the remote and
4267
// processes it.
4268
func (l *channelLink) processRemoteCommitSig(ctx context.Context,
4269
        msg *lnwire.CommitSig) error {
1,205✔
4270

1,205✔
4271
        // Since we may have learned new preimages for the first time, we'll add
1,205✔
4272
        // them to our preimage cache. By doing this, we ensure any contested
1,205✔
4273
        // contracts watched by any on-chain arbitrators can now sweep this HTLC
1,205✔
4274
        // on-chain. We delay committing the preimages until just before
1,205✔
4275
        // accepting the new remote commitment, as afterwards the peer won't
1,205✔
4276
        // resend the Settle messages on the next channel reestablishment. Doing
1,205✔
4277
        // so allows us to more effectively batch this operation, instead of
1,205✔
4278
        // doing a single write per preimage.
1,205✔
4279
        err := l.cfg.PreimageCache.AddPreimages(l.uncommittedPreimages...)
1,205✔
4280
        if err != nil {
1,205✔
4281
                l.failf(
×
4282
                        LinkFailureError{code: ErrInternalError},
×
4283
                        "unable to add preimages=%v to cache: %v",
×
4284
                        l.uncommittedPreimages, err,
×
4285
                )
×
4286

×
4287
                return err
×
4288
        }
×
4289

4290
        // Instead of truncating the slice to conserve memory allocations, we
4291
        // simply set the uncommitted preimage slice to nil so that a new one
4292
        // will be initialized if any more witnesses are discovered. We do this
4293
        // because the maximum size that the slice can occupy is 15KB, and we
4294
        // want to ensure we release that memory back to the runtime.
4295
        l.uncommittedPreimages = nil
1,205✔
4296

1,205✔
4297
        // We just received a new updates to our local commitment chain,
1,205✔
4298
        // validate this new commitment, closing the link if invalid.
1,205✔
4299
        auxSigBlob, err := msg.CustomRecords.Serialize()
1,205✔
4300
        if err != nil {
1,205✔
4301
                l.failf(
×
4302
                        LinkFailureError{code: ErrInvalidCommitment},
×
4303
                        "unable to serialize custom records: %v", err,
×
4304
                )
×
4305

×
4306
                return err
×
4307
        }
×
4308
        err = l.channel.ReceiveNewCommitment(&lnwallet.CommitSigs{
1,205✔
4309
                CommitSig:  msg.CommitSig,
1,205✔
4310
                HtlcSigs:   msg.HtlcSigs,
1,205✔
4311
                PartialSig: msg.PartialSig,
1,205✔
4312
                AuxSigBlob: auxSigBlob,
1,205✔
4313
        })
1,205✔
4314
        if err != nil {
1,205✔
4315
                // If we were unable to reconstruct their proposed commitment,
×
4316
                // then we'll examine the type of error. If it's an
×
4317
                // InvalidCommitSigError, then we'll send a direct error.
×
4318
                var sendData []byte
×
4319
                switch {
×
4320
                case lnutils.ErrorAs[*lnwallet.InvalidCommitSigError](err):
×
4321
                        sendData = []byte(err.Error())
×
4322
                case lnutils.ErrorAs[*lnwallet.InvalidHtlcSigError](err):
×
4323
                        sendData = []byte(err.Error())
×
4324
                }
4325
                l.failf(
×
4326
                        LinkFailureError{
×
4327
                                code:          ErrInvalidCommitment,
×
4328
                                FailureAction: LinkFailureForceClose,
×
4329
                                SendData:      sendData,
×
4330
                        },
×
4331
                        "ChannelPoint(%v): unable to accept new "+
×
4332
                                "commitment: %v",
×
4333
                        l.channel.ChannelPoint(), err,
×
4334
                )
×
4335

×
4336
                return err
×
4337
        }
4338

4339
        // As we've just accepted a new state, we'll now immediately send the
4340
        // remote peer a revocation for our prior state.
4341
        nextRevocation, currentHtlcs, finalHTLCs, err :=
1,205✔
4342
                l.channel.RevokeCurrentCommitment()
1,205✔
4343
        if err != nil {
1,205✔
4344
                l.log.Errorf("unable to revoke commitment: %v", err)
×
4345

×
4346
                // We need to fail the channel in case revoking our local
×
4347
                // commitment does not succeed. We might have already advanced
×
4348
                // our channel state which would lead us to proceed with an
×
4349
                // unclean state.
×
4350
                //
×
4351
                // NOTE: We do not trigger a force close because this could
×
4352
                // resolve itself in case our db was just busy not accepting new
×
4353
                // transactions.
×
4354
                l.failf(
×
4355
                        LinkFailureError{
×
4356
                                code:          ErrInternalError,
×
4357
                                Warning:       true,
×
4358
                                FailureAction: LinkFailureDisconnect,
×
4359
                        },
×
4360
                        "ChannelPoint(%v): unable to accept new "+
×
4361
                                "commitment: %v",
×
4362
                        l.channel.ChannelPoint(), err,
×
4363
                )
×
4364

×
4365
                return err
×
4366
        }
×
4367

4368
        // As soon as we are ready to send our next revocation, we can invoke
4369
        // the incoming commit hooks.
4370
        l.Lock()
1,205✔
4371
        l.incomingCommitHooks.invoke()
1,205✔
4372
        l.Unlock()
1,205✔
4373

1,205✔
4374
        err = l.cfg.Peer.SendMessage(false, nextRevocation)
1,205✔
4375
        if err != nil {
1,205✔
4376
                l.log.Errorf("failed to send RevokeAndAck: %v", err)
×
4377
        }
×
4378

4379
        // Notify the incoming htlcs of which the resolutions were locked in.
4380
        for id, settled := range finalHTLCs {
1,539✔
4381
                l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
334✔
4382
                        models.CircuitKey{
334✔
4383
                                ChanID: l.ShortChanID(),
334✔
4384
                                HtlcID: id,
334✔
4385
                        },
334✔
4386
                        channeldb.FinalHtlcInfo{
334✔
4387
                                Settled:  settled,
334✔
4388
                                Offchain: true,
334✔
4389
                        },
334✔
4390
                )
334✔
4391
        }
334✔
4392

4393
        // Since we just revoked our commitment, we may have a new set of HTLC's
4394
        // on our commitment, so we'll send them using our function closure
4395
        // NotifyContractUpdate.
4396
        newUpdate := &contractcourt.ContractUpdate{
1,205✔
4397
                HtlcKey: contractcourt.LocalHtlcSet,
1,205✔
4398
                Htlcs:   currentHtlcs,
1,205✔
4399
        }
1,205✔
4400
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,205✔
4401
        if err != nil {
1,205✔
4402
                return fmt.Errorf("unable to notify contract update: %w", err)
×
4403
        }
×
4404

4405
        select {
1,205✔
4406
        case <-l.cg.Done():
×
4407
                return nil
×
4408
        default:
1,205✔
4409
        }
4410

4411
        // If the remote party initiated the state transition, we'll reply with
4412
        // a signature to provide them with their version of the latest
4413
        // commitment. Otherwise, both commitment chains are fully synced from
4414
        // our PoV, then we don't need to reply with a signature as both sides
4415
        // already have a commitment with the latest accepted.
4416
        if l.channel.OweCommitment() {
1,874✔
4417
                if !l.updateCommitTxOrFail(ctx) {
669✔
4418
                        return nil
×
4419
                }
×
4420
        }
4421

4422
        // If we need to send out an Stfu, this would be the time to do so.
4423
        if l.noDanglingUpdates(lntypes.Local) {
2,284✔
4424
                err = l.quiescer.SendOwedStfu()
1,079✔
4425
                if err != nil {
1,079✔
4426
                        l.stfuFailf("sendOwedStfu: %v", err)
×
4427
                }
×
4428
        }
4429

4430
        // Now that we have finished processing the incoming CommitSig and sent
4431
        // out our RevokeAndAck, we invoke the flushHooks if the channel state
4432
        // is clean.
4433
        l.Lock()
1,205✔
4434
        if l.channel.IsChannelClean() {
1,394✔
4435
                l.flushHooks.invoke()
189✔
4436
        }
189✔
4437
        l.Unlock()
1,205✔
4438

1,205✔
4439
        return nil
1,205✔
4440
}
4441

4442
// processRemoteRevokeAndAck takes a `RevokeAndAck` msg sent from the remote and
4443
// processes it.
4444
func (l *channelLink) processRemoteRevokeAndAck(ctx context.Context,
4445
        msg *lnwire.RevokeAndAck) error {
1,194✔
4446

1,194✔
4447
        // We've received a revocation from the remote chain, if valid, this
1,194✔
4448
        // moves the remote chain forward, and expands our revocation window.
1,194✔
4449

1,194✔
4450
        // We now process the message and advance our remote commit chain.
1,194✔
4451
        fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
1,194✔
4452
        if err != nil {
1,194✔
4453
                // TODO(halseth): force close?
×
4454
                l.failf(
×
4455
                        LinkFailureError{
×
4456
                                code:          ErrInvalidRevocation,
×
4457
                                FailureAction: LinkFailureDisconnect,
×
4458
                        },
×
4459
                        "unable to accept revocation: %v", err,
×
4460
                )
×
4461

×
4462
                return err
×
4463
        }
×
4464

4465
        // The remote party now has a new primary commitment, so we'll update
4466
        // the contract court to be aware of this new set (the prior old remote
4467
        // pending).
4468
        newUpdate := &contractcourt.ContractUpdate{
1,194✔
4469
                HtlcKey: contractcourt.RemoteHtlcSet,
1,194✔
4470
                Htlcs:   remoteHTLCs,
1,194✔
4471
        }
1,194✔
4472
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,194✔
4473
        if err != nil {
1,194✔
4474
                return fmt.Errorf("unable to notify contract update: %w", err)
×
4475
        }
×
4476

4477
        select {
1,194✔
UNCOV
4478
        case <-l.cg.Done():
×
UNCOV
4479
                return nil
×
4480
        default:
1,194✔
4481
        }
4482

4483
        // If we have a tower client for this channel type, we'll create a
4484
        // backup for the current state.
4485
        if l.cfg.TowerClient != nil {
1,197✔
4486
                state := l.channel.State()
3✔
4487
                chanID := l.ChanID()
3✔
4488

3✔
4489
                err = l.cfg.TowerClient.BackupState(
3✔
4490
                        &chanID, state.RemoteCommitment.CommitHeight-1,
3✔
4491
                )
3✔
4492
                if err != nil {
3✔
4493
                        l.failf(LinkFailureError{
×
4494
                                code: ErrInternalError,
×
4495
                        }, "unable to queue breach backup: %v", err)
×
4496

×
4497
                        return err
×
4498
                }
×
4499
        }
4500

4501
        // If we can send updates then we can process adds in case we are the
4502
        // exit hop and need to send back resolutions, or in case there are
4503
        // validity issues with the packets. Otherwise we defer the action until
4504
        // resume.
4505
        //
4506
        // We are free to process the settles and fails without this check since
4507
        // processing those can't result in further updates to this channel
4508
        // link.
4509
        if l.quiescer.CanSendUpdates() {
2,387✔
4510
                l.processRemoteAdds(fwdPkg)
1,193✔
4511
        } else {
1,194✔
4512
                l.quiescer.OnResume(func() {
1✔
4513
                        l.processRemoteAdds(fwdPkg)
×
4514
                })
×
4515
        }
4516
        l.processRemoteSettleFails(fwdPkg)
1,194✔
4517

1,194✔
4518
        // If the link failed during processing the adds, we must return to
1,194✔
4519
        // ensure we won't attempted to update the state further.
1,194✔
4520
        if l.failed {
1,194✔
4521
                return nil
×
4522
        }
×
4523

4524
        // The revocation window opened up. If there are pending local updates,
4525
        // try to update the commit tx. Pending updates could already have been
4526
        // present because of a previously failed update to the commit tx or
4527
        // freshly added in by processRemoteAdds. Also in case there are no
4528
        // local updates, but there are still remote updates that are not in the
4529
        // remote commit tx yet, send out an update.
4530
        if l.channel.OweCommitment() {
1,525✔
4531
                if !l.updateCommitTxOrFail(ctx) {
338✔
4532
                        return nil
7✔
4533
                }
7✔
4534
        }
4535

4536
        // Now that we have finished processing the RevokeAndAck, we can invoke
4537
        // the flushHooks if the channel state is clean.
4538
        l.Lock()
1,187✔
4539
        if l.channel.IsChannelClean() {
1,351✔
4540
                l.flushHooks.invoke()
164✔
4541
        }
164✔
4542
        l.Unlock()
1,187✔
4543

1,187✔
4544
        return nil
1,187✔
4545
}
4546

4547
// processRemoteUpdateFee takes an `UpdateFee` msg sent from the remote and
4548
// processes it.
4549
func (l *channelLink) processRemoteUpdateFee(msg *lnwire.UpdateFee) error {
3✔
4550
        // Check and see if their proposed fee-rate would make us exceed the fee
3✔
4551
        // threshold.
3✔
4552
        fee := chainfee.SatPerKWeight(msg.FeePerKw)
3✔
4553

3✔
4554
        isDust, err := l.exceedsFeeExposureLimit(fee)
3✔
4555
        if err != nil {
3✔
4556
                // This shouldn't typically happen. If it does, it indicates
×
4557
                // something is wrong with our channel state.
×
4558
                l.log.Errorf("Unable to determine if fee threshold " +
×
4559
                        "exceeded")
×
4560
                l.failf(LinkFailureError{code: ErrInternalError},
×
4561
                        "error calculating fee exposure: %v", err)
×
4562

×
4563
                return err
×
4564
        }
×
4565

4566
        if isDust {
3✔
4567
                // The proposed fee-rate makes us exceed the fee threshold.
×
4568
                l.failf(LinkFailureError{code: ErrInternalError},
×
4569
                        "fee threshold exceeded: %v", err)
×
4570
                return err
×
4571
        }
×
4572

4573
        // We received fee update from peer. If we are the initiator we will
4574
        // fail the channel, if not we will apply the update.
4575
        if err := l.channel.ReceiveUpdateFee(fee); err != nil {
3✔
4576
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
4577
                        "error receiving fee update: %v", err)
×
4578
                return err
×
4579
        }
×
4580

4581
        // Update the mailbox's feerate as well.
4582
        l.mailBox.SetFeeRate(fee)
3✔
4583

3✔
4584
        return nil
3✔
4585
}
4586

4587
// processRemoteError takes an `Error` msg sent from the remote and fails the
4588
// channel link.
4589
func (l *channelLink) processRemoteError(msg *lnwire.Error) {
2✔
4590
        // Error received from remote, MUST fail channel, but should only print
2✔
4591
        // the contents of the error message if all characters are printable
2✔
4592
        // ASCII.
2✔
4593
        l.failf(
2✔
4594
                // TODO(halseth): we currently don't fail the channel
2✔
4595
                // permanently, as there are some sync issues with other
2✔
4596
                // implementations that will lead to them sending an
2✔
4597
                // error message, but we can recover from on next
2✔
4598
                // connection. See
2✔
4599
                // https://github.com/ElementsProject/lightning/issues/4212
2✔
4600
                LinkFailureError{
2✔
4601
                        code:             ErrRemoteError,
2✔
4602
                        PermanentFailure: false,
2✔
4603
                },
2✔
4604
                "ChannelPoint(%v): received error from peer: %v",
2✔
4605
                l.channel.ChannelPoint(), msg.Error(),
2✔
4606
        )
2✔
4607
}
2✔
4608

4609
// processLocalUpdateFulfillHTLC takes an `UpdateFulfillHTLC` from the local and
4610
// processes it.
4611
func (l *channelLink) processLocalUpdateFulfillHTLC(ctx context.Context,
4612
        pkt *htlcPacket, htlc *lnwire.UpdateFulfillHTLC) {
26✔
4613

26✔
4614
        // If hodl.SettleOutgoing mode is active, we exit early to simulate
26✔
4615
        // arbitrary delays between the switch adding the SETTLE to the mailbox,
26✔
4616
        // and the HTLC being added to the commitment state.
26✔
4617
        if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
26✔
4618
                l.log.Warnf(hodl.SettleOutgoing.Warning())
×
4619
                l.mailBox.AckPacket(pkt.inKey())
×
4620

×
4621
                return
×
4622
        }
×
4623

4624
        // An HTLC we forward to the switch has just settled somewhere upstream.
4625
        // Therefore we settle the HTLC within the our local state machine.
4626
        inKey := pkt.inKey()
26✔
4627
        err := l.channel.SettleHTLC(
26✔
4628
                htlc.PaymentPreimage, pkt.incomingHTLCID, pkt.sourceRef,
26✔
4629
                pkt.destRef, &inKey,
26✔
4630
        )
26✔
4631
        if err != nil {
26✔
4632
                l.log.Errorf("unable to settle incoming HTLC for "+
×
4633
                        "circuit-key=%v: %v", inKey, err)
×
4634

×
4635
                // If the HTLC index for Settle response was not known to our
×
4636
                // commitment state, it has already been cleaned up by a prior
×
4637
                // response. We'll thus try to clean up any lingering state to
×
4638
                // ensure we don't continue reforwarding.
×
4639
                if lnutils.ErrorAs[lnwallet.ErrUnknownHtlcIndex](err) {
×
4640
                        l.cleanupSpuriousResponse(pkt)
×
4641
                }
×
4642

4643
                // Remove the packet from the link's mailbox to ensure it
4644
                // doesn't get replayed after a reconnection.
4645
                l.mailBox.AckPacket(inKey)
×
4646

×
4647
                return
×
4648
        }
4649

4650
        l.log.Debugf("queueing removal of SETTLE closed circuit: %s->%s",
26✔
4651
                pkt.inKey(), pkt.outKey())
26✔
4652

26✔
4653
        l.closedCircuits = append(l.closedCircuits, pkt.inKey())
26✔
4654

26✔
4655
        // With the HTLC settled, we'll need to populate the wire message to
26✔
4656
        // target the specific channel and HTLC to be canceled.
26✔
4657
        htlc.ChanID = l.ChanID()
26✔
4658
        htlc.ID = pkt.incomingHTLCID
26✔
4659

26✔
4660
        // Then we send the HTLC settle message to the connected peer so we can
26✔
4661
        // continue the propagation of the settle message.
26✔
4662
        err = l.cfg.Peer.SendMessage(false, htlc)
26✔
4663
        if err != nil {
26✔
4664
                l.log.Errorf("failed to send UpdateFulfillHTLC: %v", err)
×
4665
        }
×
4666

4667
        // Send a settle event notification to htlcNotifier.
4668
        l.cfg.HtlcNotifier.NotifySettleEvent(
26✔
4669
                newHtlcKey(pkt), htlc.PaymentPreimage, getEventType(pkt),
26✔
4670
        )
26✔
4671

26✔
4672
        // Immediately update the commitment tx to minimize latency.
26✔
4673
        l.updateCommitTxOrFail(ctx)
26✔
4674
}
4675

4676
// processLocalUpdateFailHTLC takes an `UpdateFailHTLC` from the local and
4677
// processes it.
4678
func (l *channelLink) processLocalUpdateFailHTLC(ctx context.Context,
4679
        pkt *htlcPacket, htlc *lnwire.UpdateFailHTLC) {
21✔
4680

21✔
4681
        // If hodl.FailOutgoing mode is active, we exit early to simulate
21✔
4682
        // arbitrary delays between the switch adding a FAIL to the mailbox, and
21✔
4683
        // the HTLC being added to the commitment state.
21✔
4684
        if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
21✔
4685
                l.log.Warnf(hodl.FailOutgoing.Warning())
×
4686
                l.mailBox.AckPacket(pkt.inKey())
×
4687

×
4688
                return
×
4689
        }
×
4690

4691
        // An HTLC cancellation has been triggered somewhere upstream, we'll
4692
        // remove then HTLC from our local state machine.
4693
        inKey := pkt.inKey()
21✔
4694
        err := l.channel.FailHTLC(
21✔
4695
                pkt.incomingHTLCID, htlc.Reason, pkt.sourceRef, pkt.destRef,
21✔
4696
                &inKey,
21✔
4697
        )
21✔
4698
        if err != nil {
26✔
4699
                l.log.Errorf("unable to cancel incoming HTLC for "+
5✔
4700
                        "circuit-key=%v: %v", inKey, err)
5✔
4701

5✔
4702
                // If the HTLC index for Fail response was not known to our
5✔
4703
                // commitment state, it has already been cleaned up by a prior
5✔
4704
                // response. We'll thus try to clean up any lingering state to
5✔
4705
                // ensure we don't continue reforwarding.
5✔
4706
                if lnutils.ErrorAs[lnwallet.ErrUnknownHtlcIndex](err) {
7✔
4707
                        l.cleanupSpuriousResponse(pkt)
2✔
4708
                }
2✔
4709

4710
                // Remove the packet from the link's mailbox to ensure it
4711
                // doesn't get replayed after a reconnection.
4712
                l.mailBox.AckPacket(inKey)
5✔
4713

5✔
4714
                return
5✔
4715
        }
4716

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

19✔
4720
        l.closedCircuits = append(l.closedCircuits, pkt.inKey())
19✔
4721

19✔
4722
        // With the HTLC removed, we'll need to populate the wire message to
19✔
4723
        // target the specific channel and HTLC to be canceled. The "Reason"
19✔
4724
        // field will have already been set within the switch.
19✔
4725
        htlc.ChanID = l.ChanID()
19✔
4726
        htlc.ID = pkt.incomingHTLCID
19✔
4727

19✔
4728
        // We send the HTLC message to the peer which initially created the
19✔
4729
        // HTLC. If the incoming blinding point is non-nil, we know that we are
19✔
4730
        // a relaying node in a blinded path. Otherwise, we're either an
19✔
4731
        // introduction node or not part of a blinded path at all.
19✔
4732
        err = l.sendIncomingHTLCFailureMsg(htlc.ID, pkt.obfuscator, htlc.Reason)
19✔
4733
        if err != nil {
19✔
4734
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
4735

×
4736
                return
×
4737
        }
×
4738

4739
        // If the packet does not have a link failure set, it failed further
4740
        // down the route so we notify a forwarding failure. Otherwise, we
4741
        // notify a link failure because it failed at our node.
4742
        if pkt.linkFailure != nil {
32✔
4743
                l.cfg.HtlcNotifier.NotifyLinkFailEvent(
13✔
4744
                        newHtlcKey(pkt), newHtlcInfo(pkt), getEventType(pkt),
13✔
4745
                        pkt.linkFailure, false,
13✔
4746
                )
13✔
4747
        } else {
22✔
4748
                l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
9✔
4749
                        newHtlcKey(pkt), getEventType(pkt),
9✔
4750
                )
9✔
4751
        }
9✔
4752

4753
        // Immediately update the commitment tx to minimize latency.
4754
        l.updateCommitTxOrFail(ctx)
19✔
4755
}
4756

4757
// validateHtlcAmount checks if the HTLC amount is within the policy's
4758
// minimum and maximum limits. Returns a LinkError if validation fails.
4759
func (l *channelLink) validateHtlcAmount(policy models.ForwardingPolicy,
4760
        payHash [32]byte, amt lnwire.MilliSatoshi,
4761
        originalScid lnwire.ShortChannelID,
4762
        customRecords lnwire.CustomRecords) *LinkError {
452✔
4763

452✔
4764
        // In case we are dealing with a custom HTLC, we don't need to validate
452✔
4765
        // the HTLC constraints.
452✔
4766
        //
452✔
4767
        // NOTE: Custom HTLCs are only locally sourced and will use custom
452✔
4768
        // channels which are not routable channels and should have their policy
452✔
4769
        // not restricted in the first place. However to be sure we skip this
452✔
4770
        // check otherwise we might end up in a loop of sending to the same
452✔
4771
        // route again and again because link errors are not persisted in
452✔
4772
        // mission control.
452✔
4773
        if fn.MapOptionZ(
452✔
4774
                l.cfg.AuxTrafficShaper,
452✔
4775
                func(ts AuxTrafficShaper) bool {
452✔
4776
                        return ts.IsCustomHTLC(customRecords)
×
4777
                },
×
4778
        ) {
×
4779

×
4780
                l.log.Debugf("Skipping htlc amount policy validation for " +
×
4781
                        "custom htlc")
×
4782

×
4783
                return nil
×
4784
        }
×
4785

4786
        // As our first sanity check, we'll ensure that the passed HTLC isn't
4787
        // too small for the next hop. If so, then we'll cancel the HTLC
4788
        // directly.
4789
        if amt < policy.MinHTLCOut {
463✔
4790
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
11✔
4791
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
11✔
4792
                        amt)
11✔
4793

11✔
4794
                // As part of the returned error, we'll send our latest routing
11✔
4795
                // policy so the sending node obtains the most up to date data.
11✔
4796
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
22✔
4797
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
11✔
4798
                }
11✔
4799
                failure := l.createFailureWithUpdate(false, originalScid, cb)
11✔
4800

11✔
4801
                return NewLinkError(failure)
11✔
4802
        }
4803

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

6✔
4810
                // As part of the returned error, we'll send our latest routing
6✔
4811
                // policy so the sending node obtains the most up-to-date data.
6✔
4812
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
12✔
4813
                        return lnwire.NewTemporaryChannelFailure(upd)
6✔
4814
                }
6✔
4815
                failure := l.createFailureWithUpdate(false, originalScid, cb)
6✔
4816

6✔
4817
                return NewDetailedLinkError(
6✔
4818
                        failure, OutgoingFailureHTLCExceedsMax,
6✔
4819
                )
6✔
4820
        }
4821

4822
        return nil
441✔
4823
}
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