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

lightningnetwork / lnd / 16023836051

02 Jul 2025 11:26AM UTC coverage: 67.524% (+9.7%) from 57.803%
16023836051

Pull #10018

github

web-flow
Merge d333b2834 into 1d2e5472b
Pull Request #10018: Refactor link's long methods

495 of 766 new or added lines in 1 file covered. (64.62%)

13 existing lines in 4 files now uncovered.

135056 of 200011 relevant lines covered (67.52%)

21838.76 hits per line

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

77.26
/htlcswitch/link.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

368
        sync.RWMutex
369

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5✔
453
        return hookID
5✔
454
}
455

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

216✔
601
        return nil
216✔
602
}
603

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

783
        return out
4✔
784
}
785

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

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

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

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

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

4✔
820
        return feePerKw, nil
4✔
821
}
822

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

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

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

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

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

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

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

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

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

882
        return cb(update)
25✔
883
}
884

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

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

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

907
        var msgsToReSend []lnwire.Message
173✔
908

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1016
                // If we have any messages to retransmit, we'll do so
1017
                // immediately so we return to a synchronized state as soon as
1018
                // possible.
1019
                for _, msg := range msgsToReSend {
184✔
1020
                        err := l.cfg.Peer.SendMessage(false, msg)
11✔
1021
                        if err != nil {
11✔
NEW
1022
                                l.log.Errorf("failed to send %v: %v",
×
NEW
1023
                                        msg.MsgType(), err)
×
NEW
1024
                        }
×
1025
                }
1026

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

1031
        return nil
173✔
1032
}
1033

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

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

215✔
1047
        for _, fwdPkg := range fwdPkgs {
224✔
1048
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
9✔
1049
                        return err
×
1050
                }
×
1051
        }
1052

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

1059
        return nil
215✔
1060
}
1061

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

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

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

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

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

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

1107
        return nil
9✔
1108
}
1109

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

215✔
1119
        l.cfg.FwdPkgGCTicker.Resume()
215✔
1120
        defer l.cfg.FwdPkgGCTicker.Stop()
215✔
1121

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

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

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

1149
        var removeHeights []uint64
215✔
1150
        for _, fwdPkg := range fwdPkgs {
224✔
1151
                if fwdPkg.State != channeldb.FwdStateCompleted {
18✔
1152
                        continue
9✔
1153
                }
1154

1155
                removeHeights = append(removeHeights, fwdPkg.Height)
3✔
1156
        }
1157

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

1164
        return l.channel.RemoveFwdPkgs(removeHeights...)
3✔
1165
}
1166

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

3✔
1172
        var errDataLoss *lnwallet.ErrCommitSyncLocalDataLoss
3✔
1173

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

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

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

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

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

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

1231
        // Other, unspecified error.
1232
        default:
×
1233
        }
1234

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

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

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

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

216✔
1270
        // If the link is not started for the first time, we need to take extra
216✔
1271
        // steps to resume its state.
216✔
1272
        l.resumeLink(ctx)
216✔
1273

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

216✔
1281
        for {
4,397✔
1282
                // We must always check if we failed at some point processing
4,181✔
1283
                // the last update before processing the next.
4,181✔
1284
                if l.failed {
4,198✔
1285
                        l.log.Errorf("link failed, exiting htlcManager")
17✔
1286
                        return
17✔
1287
                }
17✔
1288

1289
                // Pause or resume the batch ticker.
1290
                l.toggleBatchTicker()
4,167✔
1291

4,167✔
1292
                select {
4,167✔
1293
                // We have a new hook that needs to be run when we reach a clean
1294
                // channel state.
1295
                case hook := <-l.flushHooks.newTransients:
4✔
1296
                        if l.channel.IsChannelClean() {
7✔
1297
                                hook()
3✔
1298
                        } else {
7✔
1299
                                l.flushHooks.alloc(hook)
4✔
1300
                        }
4✔
1301

1302
                // We have a new hook that needs to be run when we have
1303
                // committed all of our updates.
1304
                case hook := <-l.outgoingCommitHooks.newTransients:
4✔
1305
                        if !l.channel.OweCommitment() {
7✔
1306
                                hook()
3✔
1307
                        } else {
4✔
1308
                                l.outgoingCommitHooks.alloc(hook)
1✔
1309
                        }
1✔
1310

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

1320
                // Our update fee timer has fired, so we'll check the network
1321
                // fee to see if we should adjust our commitment fee.
1322
                case <-l.updateFeeTimer.C:
4✔
1323
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
4✔
1324
                        l.handleUpdateFee(ctx)
4✔
1325

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

3✔
1335
                        // TODO(roasbeef): remove all together
3✔
1336
                        go func() {
6✔
1337
                                chanPoint := l.channel.ChannelPoint()
3✔
1338
                                l.cfg.Peer.WipeChannel(&chanPoint)
3✔
1339
                        }()
3✔
1340

1341
                        return
3✔
1342

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

1352
                case <-l.cfg.PendingCommitTicker.Ticks():
1✔
1353
                        l.failf(
1✔
1354
                                LinkFailureError{
1✔
1355
                                        code:          ErrRemoteUnresponsive,
1✔
1356
                                        FailureAction: LinkFailureDisconnect,
1✔
1357
                                },
1✔
1358
                                "unable to complete dance",
1✔
1359
                        )
1✔
1360
                        return
1✔
1361

1362
                // A message from the switch was just received. This indicates
1363
                // that the link is an intermediate hop in a multi-hop HTLC
1364
                // circuit.
1365
                case pkt := <-l.downstream:
524✔
1366
                        l.handleDownstreamPkt(ctx, pkt)
524✔
1367

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

1374
                // A htlc resolution is received. This means that we now have a
1375
                // resolution for a previously accepted htlc.
1376
                case hodlItem := <-l.hodlQueue.ChanOut():
58✔
1377
                        l.handleHtlcResolution(ctx, hodlItem)
58✔
1378

1379
                // A user-initiated quiescence request is received. We now
1380
                // forward it to the quiescer.
1381
                case qReq := <-l.quiescenceReqs:
4✔
1382
                        l.handleQuiescenceReq(qReq)
4✔
1383

1384
                case <-l.cg.Done():
192✔
1385
                        return
192✔
1386
                }
1387
        }
1388
}
1389

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

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

1409
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
58✔
1410
                        return err
×
1411
                }
×
1412

1413
                // Clean up hodl map.
1414
                delete(l.hodlMap, circuitKey)
58✔
1415

58✔
1416
                select {
58✔
1417
                case item := <-l.hodlQueue.ChanOut():
3✔
1418
                        htlcResolution = item.(invoices.HtlcResolution)
3✔
1419

1420
                // No need to process it if the link is broken.
1421
                case <-l.cg.Done():
×
1422
                        return ErrLinkShuttingDown
×
1423

1424
                default:
58✔
1425
                        break loop
58✔
1426
                }
1427
        }
1428

1429
        // Update the commitment tx.
1430
        if err := l.updateCommitTx(ctx); err != nil {
59✔
1431
                return err
1✔
1432
        }
1✔
1433

1434
        return nil
57✔
1435
}
1436

1437
// processHtlcResolution applies a received htlc resolution to the provided
1438
// htlc. When this function returns without an error, the commit tx should be
1439
// updated.
1440
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1441
        htlc hodlHtlc) error {
204✔
1442

204✔
1443
        circuitKey := resolution.CircuitKey()
204✔
1444

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

200✔
1454
                return l.settleHTLC(
200✔
1455
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
200✔
1456
                )
200✔
1457

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

7✔
1464
                // Get the lnwire failure message based on the resolution
7✔
1465
                // result.
7✔
1466
                failure := getResolutionFailure(res, htlc.add.Amount)
7✔
1467

7✔
1468
                l.sendHTLCError(
7✔
1469
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
7✔
1470
                        true,
7✔
1471
                )
7✔
1472
                return nil
7✔
1473

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

1482
// getResolutionFailure returns the wire message that a htlc resolution should
1483
// be failed with.
1484
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1485
        amount lnwire.MilliSatoshi) *LinkError {
7✔
1486

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

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

7✔
1503
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
7✔
1504
}
1505

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

1515
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1516
// downstream HTLC Switch.
1517
func (l *channelLink) handleDownstreamUpdateAdd(ctx context.Context,
1518
        pkt *htlcPacket) error {
483✔
1519

483✔
1520
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
483✔
1521
        if !ok {
483✔
1522
                return errors.New("not an UpdateAddHTLC packet")
×
1523
        }
×
1524

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

×
1531
                return NewDetailedLinkError(
×
1532
                        &lnwire.FailTemporaryChannelFailure{},
×
1533
                        OutgoingFailureLinkNotEligible,
×
1534
                )
×
1535
        }
×
1536

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

1546
        // Check if we can add the HTLC here without exceededing the max fee
1547
        // exposure threshold.
1548
        if l.isOverexposedWithHtlc(htlc, false) {
487✔
1549
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1550
                        "exposure exceeded")
4✔
1551

4✔
1552
                l.mailBox.FailAdd(pkt)
4✔
1553

4✔
1554
                return NewDetailedLinkError(
4✔
1555
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1556
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1557
                )
4✔
1558
        }
4✔
1559

1560
        // A new payment has been initiated via the downstream channel,
1561
        // so we add the new HTLC to our local log, then update the
1562
        // commitment chains.
1563
        htlc.ChanID = l.ChanID()
479✔
1564
        openCircuitRef := pkt.inKey()
479✔
1565

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

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

4✔
1588
                return NewDetailedLinkError(
4✔
1589
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1590
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1591
                )
4✔
1592
        }
4✔
1593

1594
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
478✔
1595
                "local_log_index=%v, pend_updates=%v",
478✔
1596
                htlc.PaymentHash[:], index,
478✔
1597
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
478✔
1598

478✔
1599
        pkt.outgoingChanID = l.ShortChanID()
478✔
1600
        pkt.outgoingHTLCID = index
478✔
1601
        htlc.ID = index
478✔
1602

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

478✔
1606
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
478✔
1607
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
478✔
1608

478✔
1609
        err = l.cfg.Peer.SendMessage(false, htlc)
478✔
1610
        if err != nil {
478✔
NEW
1611
                l.log.Errorf("failed to send UpdateAddHTLC: %v", err)
×
NEW
1612
        }
×
1613

1614
        // Send a forward event notification to htlcNotifier.
1615
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
478✔
1616
                newHtlcKey(pkt),
478✔
1617
                HtlcInfo{
478✔
1618
                        IncomingTimeLock: pkt.incomingTimeout,
478✔
1619
                        IncomingAmt:      pkt.incomingAmount,
478✔
1620
                        OutgoingTimeLock: htlc.Expiry,
478✔
1621
                        OutgoingAmt:      htlc.Amount,
478✔
1622
                },
478✔
1623
                getEventType(pkt),
478✔
1624
        )
478✔
1625

478✔
1626
        l.tryBatchUpdateCommitTx(ctx)
478✔
1627

478✔
1628
        return nil
478✔
1629
}
1630

1631
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1632
// Switch. Possible messages sent by the switch include requests to forward new
1633
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1634
// cleared HTLCs with the upstream peer.
1635
//
1636
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1637
func (l *channelLink) handleDownstreamPkt(ctx context.Context,
1638
        pkt *htlcPacket) {
524✔
1639

524✔
1640
        if pkt.htlc.MsgType().IsChannelUpdate() &&
524✔
1641
                !l.quiescer.CanSendUpdates() {
524✔
1642

×
1643
                l.log.Warnf("unable to process channel update. "+
×
1644
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1645

×
1646
                return
×
1647
        }
×
1648

1649
        switch htlc := pkt.htlc.(type) {
524✔
1650
        case *lnwire.UpdateAddHTLC:
483✔
1651
                // Handle add message. The returned error can be ignored,
483✔
1652
                // because it is also sent through the mailbox.
483✔
1653
                _ = l.handleDownstreamUpdateAdd(ctx, pkt)
483✔
1654

1655
        case *lnwire.UpdateFulfillHTLC:
26✔
1656
                l.processLocalUpdateFulfillHTLC(ctx, pkt, htlc)
26✔
1657

1658
        case *lnwire.UpdateFailHTLC:
21✔
1659
                l.processLocalUpdateFailHTLC(ctx, pkt, htlc)
21✔
1660
        }
1661
}
1662

1663
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1664
// full.
1665
func (l *channelLink) tryBatchUpdateCommitTx(ctx context.Context) {
478✔
1666
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
478✔
1667
        if pending < uint64(l.cfg.BatchSize) {
940✔
1668
                return
462✔
1669
        }
462✔
1670

1671
        l.updateCommitTxOrFail(ctx)
19✔
1672
}
1673

1674
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1675
// associated with this packet. If successful in doing so, it will also purge
1676
// the open circuit from the circuit map and remove the packet from the link's
1677
// mailbox.
1678
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
2✔
1679
        inKey := pkt.inKey()
2✔
1680

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

2✔
1684
        // If the htlc packet doesn't have a source reference, it is unsafe to
2✔
1685
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
2✔
1686
        if pkt.sourceRef == nil {
3✔
1687
                l.log.Errorf("unable to cleanup response for incoming "+
1✔
1688
                        "circuit-key=%v, does not contain source reference",
1✔
1689
                        inKey)
1✔
1690
                return
1✔
1691
        }
1✔
1692

1693
        // If the source reference is present,  we will try to prevent this link
1694
        // from resending the packet to the switch. To do so, we ack the AddRef
1695
        // of the incoming HTLC belonging to this link.
1696
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
1✔
1697
        if err != nil {
1✔
1698
                l.log.Errorf("unable to ack AddRef for incoming "+
×
1699
                        "circuit-key=%v: %v", inKey, err)
×
1700

×
1701
                // If this operation failed, it is unsafe to attempt removal of
×
1702
                // the destination reference or circuit, so we exit early. The
×
1703
                // cleanup may proceed with a different packet in the future
×
1704
                // that succeeds on this step.
×
1705
                return
×
1706
        }
×
1707

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

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

1✔
1729
        // With all known references acked, we can now safely delete the circuit
1✔
1730
        // from the switch's circuit map, as the state is no longer needed.
1✔
1731
        err = l.cfg.Circuits.DeleteCircuits(inKey)
1✔
1732
        if err != nil {
1✔
1733
                l.log.Errorf("unable to delete circuit for "+
×
1734
                        "circuit-key=%v: %v", inKey, err)
×
1735
        }
×
1736
}
1737

1738
// handleUpstreamMsg processes wire messages related to commitment state
1739
// updates from the upstream peer. The upstream peer is the peer whom we have a
1740
// direct channel with, updating our respective commitment chains.
1741
func (l *channelLink) handleUpstreamMsg(ctx context.Context,
1742
        msg lnwire.Message) {
3,188✔
1743

3,188✔
1744
        l.log.Tracef("receive upstream msg %v, handling now... ", msg.MsgType())
3,188✔
1745
        defer l.log.Tracef("handled upstream msg %v", msg.MsgType())
3,188✔
1746

3,188✔
1747
        // First check if the message is an update and we are capable of
3,188✔
1748
        // receiving updates right now.
3,188✔
1749
        if msg.MsgType().IsChannelUpdate() && !l.quiescer.CanRecvUpdates() {
3,188✔
1750
                l.stfuFailf("update received after stfu: %T", msg)
×
1751
                return
×
1752
        }
×
1753

1754
        switch msg := msg.(type) {
3,188✔
1755
        case *lnwire.UpdateAddHTLC:
453✔
1756
                l.processRemoteUpdateAddHTLC(msg)
453✔
1757

1758
        case *lnwire.UpdateFulfillHTLC:
230✔
1759
                l.processRemoteUpdateFulfillHTLC(msg)
230✔
1760

1761
        case *lnwire.UpdateFailMalformedHTLC:
6✔
1762
                l.processRemoteUpdateFailMalformedHTLC(msg)
6✔
1763

1764
        case *lnwire.UpdateFailHTLC:
123✔
1765
                l.processRemoteUpdateFailHTLC(msg)
123✔
1766

1767
        case *lnwire.CommitSig:
1,198✔
1768
                l.processRemoteCommitSig(ctx, msg)
1,198✔
1769

1770
        case *lnwire.RevokeAndAck:
1,187✔
1771
                l.processRemoteRevokeAndAck(ctx, msg)
1,187✔
1772

1773
        case *lnwire.UpdateFee:
3✔
1774
                l.processRemoteUpdateFee(msg)
3✔
1775

1776
        case *lnwire.Stfu:
5✔
1777
                err := l.handleStfu(msg)
5✔
1778
                if err != nil {
5✔
NEW
1779
                        l.stfuFailf("handleStfu: %v", err.Error())
×
1780
                }
×
1781

1782
        // In the case where we receive a warning message from our peer, just
1783
        // log it and move on. We choose not to disconnect from our peer,
1784
        // although we "MAY" do so according to the specification.
1785
        case *lnwire.Warning:
1✔
1786
                l.log.Warnf("received warning message from peer: %v",
1✔
1787
                        msg.Warning())
1✔
1788

1789
        case *lnwire.Error:
2✔
1790
                l.processRemoteError(msg)
2✔
1791

NEW
1792
        default:
×
NEW
1793
                l.log.Warnf("received unknown message of type %T", msg)
×
1794
        }
1795
}
1796

1797
// handleStfu implements the top-level logic for handling the Stfu message from
1798
// our peer.
1799
func (l *channelLink) handleStfu(stfu *lnwire.Stfu) error {
5✔
1800
        if !l.noDanglingUpdates(lntypes.Remote) {
5✔
NEW
1801
                return ErrPendingRemoteUpdates
×
NEW
1802
        }
×
1803
        err := l.quiescer.RecvStfu(*stfu)
5✔
1804
        if err != nil {
5✔
NEW
1805
                return err
×
NEW
1806
        }
×
1807

1808
        // If we can immediately send an Stfu response back, we will.
1809
        if l.noDanglingUpdates(lntypes.Local) {
9✔
1810
                return l.quiescer.SendOwedStfu()
4✔
1811
        }
4✔
1812

1813
        return nil
1✔
1814
}
1815

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

1828
// noDanglingUpdates returns true when there are 0 updates that were originally
1829
// issued by whose on either the Local or Remote commitment transaction.
1830
func (l *channelLink) noDanglingUpdates(whose lntypes.ChannelParty) bool {
1,203✔
1831
        pendingOnLocal := l.channel.NumPendingUpdates(
1,203✔
1832
                whose, lntypes.Local,
1,203✔
1833
        )
1,203✔
1834
        pendingOnRemote := l.channel.NumPendingUpdates(
1,203✔
1835
                whose, lntypes.Remote,
1,203✔
1836
        )
1,203✔
1837

1,203✔
1838
        return pendingOnLocal == 0 && pendingOnRemote == 0
1,203✔
1839
}
1,203✔
1840

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

1860
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
467✔
1861
                l.mailBox.AckPacket(inKey)
467✔
1862
        }
1863

1864
        // Now, we will delete all circuits closed by the previous commitment
1865
        // signature, which is the result of downstream Settle/Fail packets. We
1866
        // batch them here to ensure circuits are closed atomically and for
1867
        // performance.
1868
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
1,377✔
1869
        switch err {
1,377✔
1870
        case nil:
1,377✔
1871
                // Successful deletion.
1872

1873
        default:
×
1874
                l.log.Errorf("unable to delete %d circuits: %v",
×
1875
                        len(l.closedCircuits), err)
×
1876
                return err
×
1877
        }
1878

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

1890
        // Lastly, reset our buffers to be empty while keeping any acquired
1891
        // growth in the backing array.
1892
        l.openedCircuits = l.openedCircuits[:0]
1,377✔
1893
        l.closedCircuits = l.closedCircuits[:0]
1,377✔
1894

1,377✔
1895
        return nil
1,377✔
1896
}
1897

1898
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
1899
// the link.
1900
func (l *channelLink) updateCommitTxOrFail(ctx context.Context) bool {
1,226✔
1901
        err := l.updateCommitTx(ctx)
1,226✔
1902
        switch {
1,226✔
1903
        // No error encountered, success.
1904
        case err == nil:
1,216✔
1905

1906
        // A duplicate keystone error should be resolved and is not fatal, so
1907
        // we won't send an Error message to the peer.
NEW
1908
        case errors.Is(err, ErrDuplicateKeystone):
×
1909
                l.failf(LinkFailureError{code: ErrCircuitError},
×
1910
                        "temporary circuit error: %v", err)
×
1911
                return false
×
1912

1913
        // Any other error is treated results in an Error message being sent to
1914
        // the peer.
1915
        default:
10✔
1916
                l.failf(LinkFailureError{code: ErrInternalError},
10✔
1917
                        "unable to update commitment: %v", err)
10✔
1918
                return false
10✔
1919
        }
1920

1921
        return true
1,216✔
1922
}
1923

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

1938
        // Reset the batch, but keep the backing buffer to avoid reallocating.
1939
        l.keystoneBatch = l.keystoneBatch[:0]
1,284✔
1940

1,284✔
1941
        // If hodl.Commit mode is active, we will refrain from attempting to
1,284✔
1942
        // commit any in-memory modifications to the channel state. Exiting here
1,284✔
1943
        // permits testing of either the switch or link's ability to trim
1,284✔
1944
        // circuits that have been opened, but unsuccessfully committed.
1,284✔
1945
        if l.cfg.HodlMask.Active(hodl.Commit) {
1,291✔
1946
                l.log.Warnf(hodl.Commit.Warning())
7✔
1947
                return nil
7✔
1948
        }
7✔
1949

1950
        ctx, done := l.cg.Create(ctx)
1,280✔
1951
        defer done()
1,280✔
1952

1,280✔
1953
        newCommit, err := l.channel.SignNextCommitment(ctx)
1,280✔
1954
        if err == lnwallet.ErrNoWindow {
1,356✔
1955
                l.cfg.PendingCommitTicker.Resume()
76✔
1956
                l.log.Trace("PendingCommitTicker resumed")
76✔
1957

76✔
1958
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
76✔
1959
                l.log.Tracef("revocation window exhausted, unable to send: "+
76✔
1960
                        "%v, pend_updates=%v, dangling_closes%v", n,
76✔
1961
                        lnutils.SpewLogClosure(l.openedCircuits),
76✔
1962
                        lnutils.SpewLogClosure(l.closedCircuits))
76✔
1963

76✔
1964
                return nil
76✔
1965
        } else if err != nil {
1,283✔
1966
                return err
×
1967
        }
×
1968

1969
        if err := l.ackDownStreamPackets(); err != nil {
1,207✔
1970
                return err
×
1971
        }
×
1972

1973
        l.cfg.PendingCommitTicker.Pause()
1,207✔
1974
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
1,207✔
1975

1,207✔
1976
        // The remote party now has a new pending commitment, so we'll update
1,207✔
1977
        // the contract court to be aware of this new set (the prior old remote
1,207✔
1978
        // pending).
1,207✔
1979
        newUpdate := &contractcourt.ContractUpdate{
1,207✔
1980
                HtlcKey: contractcourt.RemotePendingHtlcSet,
1,207✔
1981
                Htlcs:   newCommit.PendingHTLCs,
1,207✔
1982
        }
1,207✔
1983
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,207✔
1984
        if err != nil {
1,207✔
1985
                l.log.Errorf("unable to notify contract update: %v", err)
×
1986
                return err
×
1987
        }
×
1988

1989
        select {
1,207✔
1990
        case <-l.cg.Done():
11✔
1991
                return ErrLinkShuttingDown
11✔
1992
        default:
1,196✔
1993
        }
1994

1995
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
1,196✔
1996
        if err != nil {
1,196✔
1997
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
1998
        }
×
1999

2000
        commitSig := &lnwire.CommitSig{
1,196✔
2001
                ChanID:        l.ChanID(),
1,196✔
2002
                CommitSig:     newCommit.CommitSig,
1,196✔
2003
                HtlcSigs:      newCommit.HtlcSigs,
1,196✔
2004
                PartialSig:    newCommit.PartialSig,
1,196✔
2005
                CustomRecords: auxBlobRecords,
1,196✔
2006
        }
1,196✔
2007
        err = l.cfg.Peer.SendMessage(false, commitSig)
1,196✔
2008
        if err != nil {
1,196✔
NEW
2009
                l.log.Errorf("failed to send CommitSig: %v", err)
×
NEW
2010
        }
×
2011

2012
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
2013
        // of commit hooks.
2014
        l.RWMutex.Lock()
1,196✔
2015
        l.outgoingCommitHooks.invoke()
1,196✔
2016
        l.RWMutex.Unlock()
1,196✔
2017

1,196✔
2018
        return nil
1,196✔
2019
}
2020

2021
// Peer returns the representation of remote peer with which we have the
2022
// channel link opened.
2023
//
2024
// NOTE: Part of the ChannelLink interface.
2025
func (l *channelLink) PeerPubKey() [33]byte {
444✔
2026
        return l.cfg.Peer.PubKey()
444✔
2027
}
444✔
2028

2029
// ChannelPoint returns the channel outpoint for the channel link.
2030
// NOTE: Part of the ChannelLink interface.
2031
func (l *channelLink) ChannelPoint() wire.OutPoint {
855✔
2032
        return l.channel.ChannelPoint()
855✔
2033
}
855✔
2034

2035
// ShortChanID returns the short channel ID for the channel link. The short
2036
// channel ID encodes the exact location in the main chain that the original
2037
// funding output can be found.
2038
//
2039
// NOTE: Part of the ChannelLink interface.
2040
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
4,252✔
2041
        l.RLock()
4,252✔
2042
        defer l.RUnlock()
4,252✔
2043

4,252✔
2044
        return l.channel.ShortChanID()
4,252✔
2045
}
4,252✔
2046

2047
// UpdateShortChanID updates the short channel ID for a link. This may be
2048
// required in the event that a link is created before the short chan ID for it
2049
// is known, or a re-org occurs, and the funding transaction changes location
2050
// within the chain.
2051
//
2052
// NOTE: Part of the ChannelLink interface.
2053
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
3✔
2054
        chanID := l.ChanID()
3✔
2055

3✔
2056
        // Refresh the channel state's short channel ID by loading it from disk.
3✔
2057
        // This ensures that the channel state accurately reflects the updated
3✔
2058
        // short channel ID.
3✔
2059
        err := l.channel.State().Refresh()
3✔
2060
        if err != nil {
3✔
2061
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
2062
                        "%v", chanID, err)
×
2063
                return hop.Source, err
×
2064
        }
×
2065

2066
        return hop.Source, nil
3✔
2067
}
2068

2069
// ChanID returns the channel ID for the channel link. The channel ID is a more
2070
// compact representation of a channel's full outpoint.
2071
//
2072
// NOTE: Part of the ChannelLink interface.
2073
func (l *channelLink) ChanID() lnwire.ChannelID {
3,936✔
2074
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
3,936✔
2075
}
3,936✔
2076

2077
// Bandwidth returns the total amount that can flow through the channel link at
2078
// this given instance. The value returned is expressed in millisatoshi and can
2079
// be used by callers when making forwarding decisions to determine if a link
2080
// can accept an HTLC.
2081
//
2082
// NOTE: Part of the ChannelLink interface.
2083
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
814✔
2084
        // Get the balance available on the channel for new HTLCs. This takes
814✔
2085
        // the channel reserve into account so HTLCs up to this value won't
814✔
2086
        // violate it.
814✔
2087
        return l.channel.AvailableBalance()
814✔
2088
}
814✔
2089

2090
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2091
// amount provided to the link. This check does not reserve a space, since
2092
// forwards or other payments may use the available slot, so it should be
2093
// considered best-effort.
2094
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
3✔
2095
        return l.channel.MayAddOutgoingHtlc(amt)
3✔
2096
}
3✔
2097

2098
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2099
// method.
2100
//
2101
// NOTE: Part of the dustHandler interface.
2102
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2103
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
2,526✔
2104

2,526✔
2105
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
2,526✔
2106
}
2,526✔
2107

2108
// getFeeRate is a wrapper method that retrieves the underlying channel's
2109
// feerate.
2110
//
2111
// NOTE: Part of the dustHandler interface.
2112
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
672✔
2113
        return l.channel.CommitFeeRate()
672✔
2114
}
672✔
2115

2116
// getDustClosure returns a closure that can be used by the switch or mailbox
2117
// to evaluate whether a given HTLC is dust.
2118
//
2119
// NOTE: Part of the dustHandler interface.
2120
func (l *channelLink) getDustClosure() dustClosure {
1,602✔
2121
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
1,602✔
2122
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
1,602✔
2123
        chanType := l.channel.State().ChanType
1,602✔
2124

1,602✔
2125
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
1,602✔
2126
}
1,602✔
2127

2128
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2129
// is used so that the Switch can have access to the commitment fee without
2130
// needing to have a *LightningChannel. This doesn't include dust.
2131
//
2132
// NOTE: Part of the dustHandler interface.
2133
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
1,894✔
2134
        if remote {
2,858✔
2135
                return l.channel.State().RemoteCommitment.CommitFee
964✔
2136
        }
964✔
2137

2138
        return l.channel.State().LocalCommitment.CommitFee
933✔
2139
}
2140

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

6✔
2155
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
6✔
2156

6✔
2157
        // Get the sum of dust for both the local and remote commitments using
6✔
2158
        // this "dry-run" fee.
6✔
2159
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
6✔
2160
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
6✔
2161

6✔
2162
        // Calculate the local and remote commitment fees using this dry-run
6✔
2163
        // fee.
6✔
2164
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
2165
        if err != nil {
6✔
2166
                return false, err
×
2167
        }
×
2168

2169
        // Finally, check whether the max fee exposure was exceeded on either
2170
        // future commitment transaction with the fee-rate.
2171
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
6✔
2172
        if totalLocalDust > l.cfg.MaxFeeExposure {
6✔
2173
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
2174
                        "local dust: %v, local fee: %v", l.ShortChanID(),
×
2175
                        totalLocalDust, localFee)
×
2176

×
2177
                return true, nil
×
2178
        }
×
2179

2180
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
6✔
2181
                remoteFee,
6✔
2182
        )
6✔
2183

6✔
2184
        if totalRemoteDust > l.cfg.MaxFeeExposure {
6✔
2185
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
2186
                        "remote dust: %v, remote fee: %v", l.ShortChanID(),
×
2187
                        totalRemoteDust, remoteFee)
×
2188

×
2189
                return true, nil
×
2190
        }
×
2191

2192
        return false, nil
6✔
2193
}
2194

2195
// isOverexposedWithHtlc calculates whether the proposed HTLC will make the
2196
// channel exceed the fee threshold. It first fetches the largest fee-rate that
2197
// may be on any unrevoked commitment transaction. Then, using this fee-rate,
2198
// determines if the to-be-added HTLC is dust. If the HTLC is dust, it adds to
2199
// the overall dust sum. If it is not dust, it contributes to weight, which
2200
// also adds to the overall dust sum by an increase in fees. If the dust sum on
2201
// either commitment exceeds the configured fee threshold, this function
2202
// returns true.
2203
func (l *channelLink) isOverexposedWithHtlc(htlc *lnwire.UpdateAddHTLC,
2204
        incoming bool) bool {
933✔
2205

933✔
2206
        dustClosure := l.getDustClosure()
933✔
2207

933✔
2208
        feeRate := l.channel.WorstCaseFeeRate()
933✔
2209

933✔
2210
        amount := htlc.Amount.ToSatoshis()
933✔
2211

933✔
2212
        // See if this HTLC is dust on both the local and remote commitments.
933✔
2213
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
933✔
2214
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
933✔
2215

933✔
2216
        // Calculate the dust sum for the local and remote commitments.
933✔
2217
        localDustSum := l.getDustSum(
933✔
2218
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
933✔
2219
        )
933✔
2220
        remoteDustSum := l.getDustSum(
933✔
2221
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
933✔
2222
        )
933✔
2223

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

933✔
2227
        if l.getCommitFee(true) > commitFee {
966✔
2228
                commitFee = l.getCommitFee(true)
33✔
2229
        }
33✔
2230

2231
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
933✔
2232

933✔
2233
        localDustSum += commitFeeMSat
933✔
2234
        remoteDustSum += commitFeeMSat
933✔
2235

933✔
2236
        // Calculate the additional fee increase if this is a non-dust HTLC.
933✔
2237
        weight := lntypes.WeightUnit(input.HTLCWeight)
933✔
2238
        additional := lnwire.NewMSatFromSatoshis(
933✔
2239
                feeRate.FeeForWeight(weight),
933✔
2240
        )
933✔
2241

933✔
2242
        if isLocalDust {
1,569✔
2243
                // If this is dust, it doesn't contribute to weight but does
636✔
2244
                // contribute to the overall dust sum.
636✔
2245
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
636✔
2246
        } else {
936✔
2247
                // Account for the fee increase that comes with an increase in
300✔
2248
                // weight.
300✔
2249
                localDustSum += additional
300✔
2250
        }
300✔
2251

2252
        if localDustSum > l.cfg.MaxFeeExposure {
937✔
2253
                // The max fee exposure was exceeded.
4✔
2254
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
4✔
2255
                        "overexposed, total local dust: %v (current commit "+
4✔
2256
                        "fee: %v)", l.ShortChanID(), htlc, localDustSum)
4✔
2257

4✔
2258
                return true
4✔
2259
        }
4✔
2260

2261
        if isRemoteDust {
1,562✔
2262
                // If this is dust, it doesn't contribute to weight but does
633✔
2263
                // contribute to the overall dust sum.
633✔
2264
                remoteDustSum += lnwire.NewMSatFromSatoshis(amount)
633✔
2265
        } else {
932✔
2266
                // Account for the fee increase that comes with an increase in
299✔
2267
                // weight.
299✔
2268
                remoteDustSum += additional
299✔
2269
        }
299✔
2270

2271
        if remoteDustSum > l.cfg.MaxFeeExposure {
929✔
2272
                // The max fee exposure was exceeded.
×
2273
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
2274
                        "overexposed, total remote dust: %v (current commit "+
×
2275
                        "fee: %v)", l.ShortChanID(), htlc, remoteDustSum)
×
2276

×
2277
                return true
×
2278
        }
×
2279

2280
        return false
929✔
2281
}
2282

2283
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
2284
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
2285
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
2286
// whether to evaluate on the local or remote commit, and finally an HTLC
2287
// amount to test.
2288
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
2289
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
2290

2291
// dustHelper is used to construct the dustClosure.
2292
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
2293
        remoteDustLimit btcutil.Amount) dustClosure {
1,802✔
2294

1,802✔
2295
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
1,802✔
2296
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
11,581✔
2297

9,779✔
2298
                var dustLimit btcutil.Amount
9,779✔
2299
                if whoseCommit.IsLocal() {
14,670✔
2300
                        dustLimit = localDustLimit
4,891✔
2301
                } else {
9,782✔
2302
                        dustLimit = remoteDustLimit
4,891✔
2303
                }
4,891✔
2304

2305
                return lnwallet.HtlcIsDust(
9,779✔
2306
                        chantype, incoming, whoseCommit, feerate, amt,
9,779✔
2307
                        dustLimit,
9,779✔
2308
                )
9,779✔
2309
        }
2310

2311
        return isDust
1,802✔
2312
}
2313

2314
// zeroConfConfirmed returns whether or not the zero-conf channel has
2315
// confirmed on-chain.
2316
//
2317
// Part of the scidAliasHandler interface.
2318
func (l *channelLink) zeroConfConfirmed() bool {
6✔
2319
        return l.channel.State().ZeroConfConfirmed()
6✔
2320
}
6✔
2321

2322
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
2323
// should not be called for non-zero-conf channels.
2324
//
2325
// Part of the scidAliasHandler interface.
2326
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
6✔
2327
        return l.channel.State().ZeroConfRealScid()
6✔
2328
}
6✔
2329

2330
// isZeroConf returns whether or not the underlying channel is a zero-conf
2331
// channel.
2332
//
2333
// Part of the scidAliasHandler interface.
2334
func (l *channelLink) isZeroConf() bool {
216✔
2335
        return l.channel.State().IsZeroConf()
216✔
2336
}
216✔
2337

2338
// negotiatedAliasFeature returns whether or not the underlying channel has
2339
// negotiated the option-scid-alias feature bit. This will be true for both
2340
// option-scid-alias and zero-conf channel-types. It will also be true for
2341
// channels with the feature bit but without the above channel-types.
2342
//
2343
// Part of the scidAliasFeature interface.
2344
func (l *channelLink) negotiatedAliasFeature() bool {
377✔
2345
        return l.channel.State().NegotiatedAliasFeature()
377✔
2346
}
377✔
2347

2348
// getAliases returns the set of aliases for the underlying channel.
2349
//
2350
// Part of the scidAliasHandler interface.
2351
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
222✔
2352
        return l.cfg.GetAliases(l.ShortChanID())
222✔
2353
}
222✔
2354

2355
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
2356
//
2357
// Part of the scidAliasHandler interface.
2358
func (l *channelLink) attachFailAliasUpdate(closure func(
2359
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
217✔
2360

217✔
2361
        l.Lock()
217✔
2362
        l.cfg.FailAliasUpdate = closure
217✔
2363
        l.Unlock()
217✔
2364
}
217✔
2365

2366
// AttachMailBox updates the current mailbox used by this link, and hooks up
2367
// the mailbox's message and packet outboxes to the link's upstream and
2368
// downstream chans, respectively.
2369
func (l *channelLink) AttachMailBox(mailbox MailBox) {
216✔
2370
        l.Lock()
216✔
2371
        l.mailBox = mailbox
216✔
2372
        l.upstream = mailbox.MessageOutBox()
216✔
2373
        l.downstream = mailbox.PacketOutBox()
216✔
2374
        l.Unlock()
216✔
2375

216✔
2376
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
216✔
2377
        // never committed.
216✔
2378
        l.mailBox.SetFeeRate(l.getFeeRate())
216✔
2379

216✔
2380
        // Also set the mailbox's dust closure so that it can query whether HTLC's
216✔
2381
        // are dust given the current feerate.
216✔
2382
        l.mailBox.SetDustClosure(l.getDustClosure())
216✔
2383
}
216✔
2384

2385
// UpdateForwardingPolicy updates the forwarding policy for the target
2386
// ChannelLink. Once updated, the link will use the new forwarding policy to
2387
// govern if it an incoming HTLC should be forwarded or not. We assume that
2388
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
2389
// update all of the link's FwrdingPolicy's values.
2390
//
2391
// NOTE: Part of the ChannelLink interface.
2392
func (l *channelLink) UpdateForwardingPolicy(
2393
        newPolicy models.ForwardingPolicy) {
15✔
2394

15✔
2395
        l.Lock()
15✔
2396
        defer l.Unlock()
15✔
2397

15✔
2398
        l.cfg.FwrdingPolicy = newPolicy
15✔
2399
}
15✔
2400

2401
// CheckHtlcForward should return a nil error if the passed HTLC details
2402
// satisfy the current forwarding policy fo the target link. Otherwise,
2403
// a LinkError with a valid protocol failure message should be returned
2404
// in order to signal to the source of the HTLC, the policy consistency
2405
// issue.
2406
//
2407
// NOTE: Part of the ChannelLink interface.
2408
func (l *channelLink) CheckHtlcForward(payHash [32]byte, incomingHtlcAmt,
2409
        amtToForward lnwire.MilliSatoshi, incomingTimeout,
2410
        outgoingTimeout uint32, inboundFee models.InboundFee,
2411
        heightNow uint32, originalScid lnwire.ShortChannelID,
2412
        customRecords lnwire.CustomRecords) *LinkError {
52✔
2413

52✔
2414
        l.RLock()
52✔
2415
        policy := l.cfg.FwrdingPolicy
52✔
2416
        l.RUnlock()
52✔
2417

52✔
2418
        // Using the outgoing HTLC amount, we'll calculate the outgoing
52✔
2419
        // fee this incoming HTLC must carry in order to satisfy the constraints
52✔
2420
        // of the outgoing link.
52✔
2421
        outFee := ExpectedFee(policy, amtToForward)
52✔
2422

52✔
2423
        // Then calculate the inbound fee that we charge based on the sum of
52✔
2424
        // outgoing HTLC amount and outgoing fee.
52✔
2425
        inFee := inboundFee.CalcFee(amtToForward + outFee)
52✔
2426

52✔
2427
        // Add up both fee components. It is important to calculate both fees
52✔
2428
        // separately. An alternative way of calculating is to first determine
52✔
2429
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
52✔
2430
        // rounding may cause the result to be slightly higher than in the case
52✔
2431
        // of separately rounded fee components. This potentially causes failed
52✔
2432
        // forwards for senders and is something to be avoided.
52✔
2433
        expectedFee := inFee + int64(outFee)
52✔
2434

52✔
2435
        // If the actual fee is less than our expected fee, then we'll reject
52✔
2436
        // this HTLC as it didn't provide a sufficient amount of fees, or the
52✔
2437
        // values have been tampered with, or the send used incorrect/dated
52✔
2438
        // information to construct the forwarding information for this hop. In
52✔
2439
        // any case, we'll cancel this HTLC.
52✔
2440
        actualFee := int64(incomingHtlcAmt) - int64(amtToForward)
52✔
2441
        if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
61✔
2442
                l.log.Warnf("outgoing htlc(%x) has insufficient fee: "+
9✔
2443
                        "expected %v, got %v: incoming=%v, outgoing=%v, "+
9✔
2444
                        "inboundFee=%v",
9✔
2445
                        payHash[:], expectedFee, actualFee,
9✔
2446
                        incomingHtlcAmt, amtToForward, inboundFee,
9✔
2447
                )
9✔
2448

9✔
2449
                // As part of the returned error, we'll send our latest routing
9✔
2450
                // policy so the sending node obtains the most up to date data.
9✔
2451
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
18✔
2452
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
9✔
2453
                }
9✔
2454
                failure := l.createFailureWithUpdate(false, originalScid, cb)
9✔
2455
                return NewLinkError(failure)
9✔
2456
        }
2457

2458
        // Check whether the outgoing htlc satisfies the channel policy.
2459
        err := l.canSendHtlc(
46✔
2460
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
46✔
2461
                originalScid, customRecords,
46✔
2462
        )
46✔
2463
        if err != nil {
62✔
2464
                return err
16✔
2465
        }
16✔
2466

2467
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
2468
        // the following constraint: the incoming time-lock minus our time-lock
2469
        // delta should equal the outgoing time lock. Otherwise, whether the
2470
        // sender messed up, or an intermediate node tampered with the HTLC.
2471
        timeDelta := policy.TimeLockDelta
33✔
2472
        if incomingTimeout < outgoingTimeout+timeDelta {
35✔
2473
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
2✔
2474
                        "expected at least %v block delta, got %v block delta",
2✔
2475
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
2✔
2476

2✔
2477
                // Grab the latest routing policy so the sending node is up to
2✔
2478
                // date with our current policy.
2✔
2479
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
2480
                        return lnwire.NewIncorrectCltvExpiry(
2✔
2481
                                incomingTimeout, *upd,
2✔
2482
                        )
2✔
2483
                }
2✔
2484
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
2485
                return NewLinkError(failure)
2✔
2486
        }
2487

2488
        return nil
31✔
2489
}
2490

2491
// CheckHtlcTransit should return a nil error if the passed HTLC details
2492
// satisfy the current channel policy.  Otherwise, a LinkError with a
2493
// valid protocol failure message should be returned in order to signal
2494
// the violation. This call is intended to be used for locally initiated
2495
// payments for which there is no corresponding incoming htlc.
2496
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
2497
        amt lnwire.MilliSatoshi, timeout uint32, heightNow uint32,
2498
        customRecords lnwire.CustomRecords) *LinkError {
409✔
2499

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

409✔
2504
        // We pass in hop.Source here as this is only used in the Switch when
409✔
2505
        // trying to send over a local link. This causes the fallback mechanism
409✔
2506
        // to occur.
409✔
2507
        return l.canSendHtlc(
409✔
2508
                policy, payHash, amt, timeout, heightNow, hop.Source,
409✔
2509
                customRecords,
409✔
2510
        )
409✔
2511
}
409✔
2512

2513
// canSendHtlc checks whether the given htlc parameters satisfy
2514
// the channel's amount and time lock constraints.
2515
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
2516
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
2517
        heightNow uint32, originalScid lnwire.ShortChannelID,
2518
        customRecords lnwire.CustomRecords) *LinkError {
452✔
2519

452✔
2520
        // As our first sanity check, we'll ensure that the passed HTLC isn't
452✔
2521
        // too small for the next hop. If so, then we'll cancel the HTLC
452✔
2522
        // directly.
452✔
2523
        if amt < policy.MinHTLCOut {
463✔
2524
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
11✔
2525
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
11✔
2526
                        amt)
11✔
2527

11✔
2528
                // As part of the returned error, we'll send our latest routing
11✔
2529
                // policy so the sending node obtains the most up to date data.
11✔
2530
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
22✔
2531
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
11✔
2532
                }
11✔
2533
                failure := l.createFailureWithUpdate(false, originalScid, cb)
11✔
2534
                return NewLinkError(failure)
11✔
2535
        }
2536

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

6✔
2543
                // As part of the returned error, we'll send our latest routing
6✔
2544
                // policy so the sending node obtains the most up-to-date data.
6✔
2545
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
12✔
2546
                        return lnwire.NewTemporaryChannelFailure(upd)
6✔
2547
                }
6✔
2548
                failure := l.createFailureWithUpdate(false, originalScid, cb)
6✔
2549
                return NewDetailedLinkError(failure, OutgoingFailureHTLCExceedsMax)
6✔
2550
        }
2551

2552
        // We want to avoid offering an HTLC which will expire in the near
2553
        // future, so we'll reject an HTLC if the outgoing expiration time is
2554
        // too close to the current height.
2555
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
443✔
2556
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
2✔
2557
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
2✔
2558
                        timeout, heightNow)
2✔
2559

2✔
2560
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
2561
                        return lnwire.NewExpiryTooSoon(*upd)
2✔
2562
                }
2✔
2563
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
2564
                return NewLinkError(failure)
2✔
2565
        }
2566

2567
        // Check absolute max delta.
2568
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
440✔
2569
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
1✔
2570
                        "the future: got %v, but maximum is %v", payHash[:],
1✔
2571
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
1✔
2572

1✔
2573
                return NewLinkError(&lnwire.FailExpiryTooFar{})
1✔
2574
        }
1✔
2575

2576
        // We now check the available bandwidth to see if this HTLC can be
2577
        // forwarded.
2578
        availableBandwidth := l.Bandwidth()
438✔
2579
        auxBandwidth, err := fn.MapOptionZ(
438✔
2580
                l.cfg.AuxTrafficShaper,
438✔
2581
                func(ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
438✔
2582
                        var htlcBlob fn.Option[tlv.Blob]
×
2583
                        blob, err := customRecords.Serialize()
×
2584
                        if err != nil {
×
2585
                                return fn.Err[OptionalBandwidth](
×
2586
                                        fmt.Errorf("unable to serialize "+
×
2587
                                                "custom records: %w", err))
×
2588
                        }
×
2589

2590
                        if len(blob) > 0 {
×
2591
                                htlcBlob = fn.Some(blob)
×
2592
                        }
×
2593

2594
                        return l.AuxBandwidth(amt, originalScid, htlcBlob, ts)
×
2595
                },
2596
        ).Unpack()
2597
        if err != nil {
438✔
2598
                l.log.Errorf("Unable to determine aux bandwidth: %v", err)
×
2599
                return NewLinkError(&lnwire.FailTemporaryNodeFailure{})
×
2600
        }
×
2601

2602
        if auxBandwidth.IsHandled && auxBandwidth.Bandwidth.IsSome() {
438✔
2603
                auxBandwidth.Bandwidth.WhenSome(
×
2604
                        func(bandwidth lnwire.MilliSatoshi) {
×
2605
                                availableBandwidth = bandwidth
×
2606
                        },
×
2607
                )
2608
        }
2609

2610
        // Check to see if there is enough balance in this channel.
2611
        if amt > availableBandwidth {
442✔
2612
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
4✔
2613
                        "larger than %v", amt, availableBandwidth)
4✔
2614
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
2615
                        return lnwire.NewTemporaryChannelFailure(upd)
4✔
2616
                }
4✔
2617
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
2618
                return NewDetailedLinkError(
4✔
2619
                        failure, OutgoingFailureInsufficientBalance,
4✔
2620
                )
4✔
2621
        }
2622

2623
        return nil
437✔
2624
}
2625

2626
// AuxBandwidth returns the bandwidth that can be used for a channel, expressed
2627
// in milli-satoshi. This might be different from the regular BTC bandwidth for
2628
// custom channels. This will always return fn.None() for a regular (non-custom)
2629
// channel.
2630
func (l *channelLink) AuxBandwidth(amount lnwire.MilliSatoshi,
2631
        cid lnwire.ShortChannelID, htlcBlob fn.Option[tlv.Blob],
2632
        ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
×
2633

×
2634
        fundingBlob := l.FundingCustomBlob()
×
2635
        shouldHandle, err := ts.ShouldHandleTraffic(cid, fundingBlob, htlcBlob)
×
2636
        if err != nil {
×
2637
                return fn.Err[OptionalBandwidth](fmt.Errorf("traffic shaper "+
×
2638
                        "failed to decide whether to handle traffic: %w", err))
×
2639
        }
×
2640

2641
        log.Debugf("ShortChannelID=%v: aux traffic shaper is handling "+
×
2642
                "traffic: %v", cid, shouldHandle)
×
2643

×
2644
        // If this channel isn't handled by the aux traffic shaper, we'll return
×
2645
        // early.
×
2646
        if !shouldHandle {
×
2647
                return fn.Ok(OptionalBandwidth{
×
2648
                        IsHandled: false,
×
2649
                })
×
2650
        }
×
2651

2652
        // Ask for a specific bandwidth to be used for the channel.
2653
        commitmentBlob := l.CommitmentCustomBlob()
×
2654
        auxBandwidth, err := ts.PaymentBandwidth(
×
2655
                fundingBlob, htlcBlob, commitmentBlob, l.Bandwidth(), amount,
×
2656
                l.channel.FetchLatestAuxHTLCView(),
×
2657
        )
×
2658
        if err != nil {
×
2659
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to get "+
×
2660
                        "bandwidth from external traffic shaper: %w", err))
×
2661
        }
×
2662

2663
        log.Debugf("ShortChannelID=%v: aux traffic shaper reported available "+
×
2664
                "bandwidth: %v", cid, auxBandwidth)
×
2665

×
2666
        return fn.Ok(OptionalBandwidth{
×
2667
                IsHandled: true,
×
2668
                Bandwidth: fn.Some(auxBandwidth),
×
2669
        })
×
2670
}
2671

2672
// Stats returns the statistics of channel link.
2673
//
2674
// NOTE: Part of the ChannelLink interface.
2675
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
7✔
2676
        snapshot := l.channel.StateSnapshot()
7✔
2677

7✔
2678
        return snapshot.ChannelCommitment.CommitHeight,
7✔
2679
                snapshot.TotalMSatSent,
7✔
2680
                snapshot.TotalMSatReceived
7✔
2681
}
7✔
2682

2683
// String returns the string representation of channel link.
2684
//
2685
// NOTE: Part of the ChannelLink interface.
2686
func (l *channelLink) String() string {
×
2687
        return l.channel.ChannelPoint().String()
×
2688
}
×
2689

2690
// handleSwitchPacket handles the switch packets. This packets which might be
2691
// forwarded to us from another channel link in case the htlc update came from
2692
// another peer or if the update was created by user
2693
//
2694
// NOTE: Part of the packetHandler interface.
2695
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
482✔
2696
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
482✔
2697
                pkt.inKey(), pkt.outKey())
482✔
2698

482✔
2699
        return l.mailBox.AddPacket(pkt)
482✔
2700
}
482✔
2701

2702
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
2703
// to us from remote peer we have a channel with.
2704
//
2705
// NOTE: Part of the ChannelLink interface.
2706
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
3,358✔
2707
        select {
3,358✔
2708
        case <-l.cg.Done():
×
2709
                // Return early if the link is already in the process of
×
2710
                // quitting. It doesn't make sense to hand the message to the
×
2711
                // mailbox here.
×
2712
                return
×
2713
        default:
3,358✔
2714
        }
2715

2716
        err := l.mailBox.AddMessage(message)
3,358✔
2717
        if err != nil {
3,358✔
2718
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
2719
        }
×
2720
}
2721

2722
// updateChannelFee updates the commitment fee-per-kw on this channel by
2723
// committing to an update_fee message.
2724
func (l *channelLink) updateChannelFee(ctx context.Context,
2725
        feePerKw chainfee.SatPerKWeight) error {
3✔
2726

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

3✔
2729
        // We skip sending the UpdateFee message if the channel is not
3✔
2730
        // currently eligible to forward messages.
3✔
2731
        if !l.eligibleToUpdate() {
3✔
2732
                l.log.Debugf("skipping fee update for inactive channel")
×
2733
                return nil
×
2734
        }
×
2735

2736
        // Check and see if our proposed fee-rate would make us exceed the fee
2737
        // threshold.
2738
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
3✔
2739
        if err != nil {
3✔
2740
                // This shouldn't typically happen. If it does, it indicates
×
2741
                // something is wrong with our channel state.
×
2742
                return err
×
2743
        }
×
2744

2745
        if thresholdExceeded {
3✔
2746
                return fmt.Errorf("link fee threshold exceeded")
×
2747
        }
×
2748

2749
        // First, we'll update the local fee on our commitment.
2750
        if err := l.channel.UpdateFee(feePerKw); err != nil {
3✔
2751
                return err
×
2752
        }
×
2753

2754
        // The fee passed the channel's validation checks, so we update the
2755
        // mailbox feerate.
2756
        l.mailBox.SetFeeRate(feePerKw)
3✔
2757

3✔
2758
        // We'll then attempt to send a new UpdateFee message, and also lock it
3✔
2759
        // in immediately by triggering a commitment update.
3✔
2760
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
3✔
2761
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
2762
                return err
×
2763
        }
×
2764

2765
        return l.updateCommitTx(ctx)
3✔
2766
}
2767

2768
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
2769
// after receiving a revocation from the remote party, and reprocesses them in
2770
// the context of the provided forwarding package. Any settles or fails that
2771
// have already been acknowledged in the forwarding package will not be sent to
2772
// the switch.
2773
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
1,186✔
2774
        if len(fwdPkg.SettleFails) == 0 {
2,057✔
2775
                l.log.Trace("fwd package has no settle/fails to process " +
871✔
2776
                        "exiting early")
871✔
2777

871✔
2778
                return
871✔
2779
        }
871✔
2780

2781
        // Exit early if the fwdPkg is already processed.
2782
        if fwdPkg.State == channeldb.FwdStateCompleted {
318✔
2783
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
2784

×
2785
                return
×
2786
        }
×
2787

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

318✔
2790
        var switchPackets []*htlcPacket
318✔
2791
        for i, update := range fwdPkg.SettleFails {
636✔
2792
                destRef := fwdPkg.DestRef(uint16(i))
318✔
2793

318✔
2794
                // Skip any settles or fails that have already been
318✔
2795
                // acknowledged by the incoming link that originated the
318✔
2796
                // forwarded Add.
318✔
2797
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
318✔
2798
                        continue
×
2799
                }
2800

2801
                // TODO(roasbeef): rework log entries to a shared
2802
                // interface.
2803

2804
                switch msg := update.UpdateMsg.(type) {
318✔
2805
                // A settle for an HTLC we previously forwarded HTLC has been
2806
                // received. So we'll forward the HTLC to the switch which will
2807
                // handle propagating the settle to the prior hop.
2808
                case *lnwire.UpdateFulfillHTLC:
195✔
2809
                        // If hodl.SettleIncoming is requested, we will not
195✔
2810
                        // forward the SETTLE to the switch and will not signal
195✔
2811
                        // a free slot on the commitment transaction.
195✔
2812
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
195✔
2813
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
2814
                                continue
×
2815
                        }
2816

2817
                        settlePacket := &htlcPacket{
195✔
2818
                                outgoingChanID: l.ShortChanID(),
195✔
2819
                                outgoingHTLCID: msg.ID,
195✔
2820
                                destRef:        &destRef,
195✔
2821
                                htlc:           msg,
195✔
2822
                        }
195✔
2823

195✔
2824
                        // Add the packet to the batch to be forwarded, and
195✔
2825
                        // notify the overflow queue that a spare spot has been
195✔
2826
                        // freed up within the commitment state.
195✔
2827
                        switchPackets = append(switchPackets, settlePacket)
195✔
2828

2829
                // A failureCode message for a previously forwarded HTLC has
2830
                // been received. As a result a new slot will be freed up in
2831
                // our commitment state, so we'll forward this to the switch so
2832
                // the backwards undo can continue.
2833
                case *lnwire.UpdateFailHTLC:
126✔
2834
                        // If hodl.SettleIncoming is requested, we will not
126✔
2835
                        // forward the FAIL to the switch and will not signal a
126✔
2836
                        // free slot on the commitment transaction.
126✔
2837
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
126✔
2838
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
2839
                                continue
×
2840
                        }
2841

2842
                        // Fetch the reason the HTLC was canceled so we can
2843
                        // continue to propagate it. This failure originated
2844
                        // from another node, so the linkFailure field is not
2845
                        // set on the packet.
2846
                        failPacket := &htlcPacket{
126✔
2847
                                outgoingChanID: l.ShortChanID(),
126✔
2848
                                outgoingHTLCID: msg.ID,
126✔
2849
                                destRef:        &destRef,
126✔
2850
                                htlc:           msg,
126✔
2851
                        }
126✔
2852

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

126✔
2855
                        // If the failure message lacks an HMAC (but includes
126✔
2856
                        // the 4 bytes for encoding the message and padding
126✔
2857
                        // lengths, then this means that we received it as an
126✔
2858
                        // UpdateFailMalformedHTLC. As a result, we'll signal
126✔
2859
                        // that we need to convert this error within the switch
126✔
2860
                        // to an actual error, by encrypting it as if we were
126✔
2861
                        // the originating hop.
126✔
2862
                        convertedErrorSize := lnwire.FailureMessageLength + 4
126✔
2863
                        if len(msg.Reason) == convertedErrorSize {
132✔
2864
                                failPacket.convertedError = true
6✔
2865
                        }
6✔
2866

2867
                        // Add the packet to the batch to be forwarded, and
2868
                        // notify the overflow queue that a spare spot has been
2869
                        // freed up within the commitment state.
2870
                        switchPackets = append(switchPackets, failPacket)
126✔
2871
                }
2872
        }
2873

2874
        // Only spawn the task forward packets we have a non-zero number.
2875
        if len(switchPackets) > 0 {
636✔
2876
                go l.forwardBatch(false, switchPackets...)
318✔
2877
        }
318✔
2878
}
2879

2880
// processRemoteAdds serially processes each of the Add payment descriptors
2881
// which have been "locked-in" by receiving a revocation from the remote party.
2882
// The forwarding package provided instructs how to process this batch,
2883
// indicating whether this is the first time these Adds are being processed, or
2884
// whether we are reprocessing as a result of a failure or restart. Adds that
2885
// have already been acknowledged in the forwarding package will be ignored.
2886
//
2887
//nolint:funlen
2888
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
1,188✔
2889
        // Exit early if there are no adds to process.
1,188✔
2890
        if len(fwdPkg.Adds) == 0 {
2,061✔
2891
                l.log.Trace("fwd package has no adds to process exiting early")
873✔
2892

873✔
2893
                return
873✔
2894
        }
873✔
2895

2896
        // Exit early if the fwdPkg is already processed.
2897
        if fwdPkg.State == channeldb.FwdStateCompleted {
318✔
2898
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
2899

×
2900
                return
×
2901
        }
×
2902

2903
        l.log.Tracef("processing %d remote adds for height %d",
318✔
2904
                len(fwdPkg.Adds), fwdPkg.Height)
318✔
2905

318✔
2906
        // decodeReqs is a list of requests sent to the onion decoder. We expect
318✔
2907
        // the same length of responses to be returned.
318✔
2908
        decodeReqs := make([]hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds))
318✔
2909

318✔
2910
        // unackedAdds is a list of ADDs that's waiting for the remote's
318✔
2911
        // settle/fail update.
318✔
2912
        unackedAdds := make([]*lnwire.UpdateAddHTLC, 0, len(fwdPkg.Adds))
318✔
2913

318✔
2914
        for i, update := range fwdPkg.Adds {
770✔
2915
                // If this index is already found in the ack filter, the
452✔
2916
                // response to this forwarding decision has already been
452✔
2917
                // committed by one of our commitment txns. ADDs in this state
452✔
2918
                // are waiting for the rest of the fwding package to get acked
452✔
2919
                // before being garbage collected.
452✔
2920
                if fwdPkg.State == channeldb.FwdStateProcessed &&
452✔
2921
                        fwdPkg.AckFilter.Contains(uint16(i)) {
452✔
2922

×
2923
                        continue
×
2924
                }
2925

2926
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
904✔
2927
                        // Before adding the new htlc to the state machine,
452✔
2928
                        // parse the onion object in order to obtain the
452✔
2929
                        // routing information with DecodeHopIterator function
452✔
2930
                        // which process the Sphinx packet.
452✔
2931
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
452✔
2932

452✔
2933
                        req := hop.DecodeHopIteratorRequest{
452✔
2934
                                OnionReader:    onionReader,
452✔
2935
                                RHash:          msg.PaymentHash[:],
452✔
2936
                                IncomingCltv:   msg.Expiry,
452✔
2937
                                IncomingAmount: msg.Amount,
452✔
2938
                                BlindingPoint:  msg.BlindingPoint,
452✔
2939
                        }
452✔
2940

452✔
2941
                        decodeReqs = append(decodeReqs, req)
452✔
2942
                        unackedAdds = append(unackedAdds, msg)
452✔
2943
                }
452✔
2944
        }
2945

2946
        // If the fwdPkg has already been processed, it means we are
2947
        // reforwarding the packets again, which happens only on a restart.
2948
        reforward := fwdPkg.State == channeldb.FwdStateProcessed
318✔
2949

318✔
2950
        // Atomically decode the incoming htlcs, simultaneously checking for
318✔
2951
        // replay attempts. A particular index in the returned, spare list of
318✔
2952
        // channel iterators should only be used if the failure code at the
318✔
2953
        // same index is lnwire.FailCodeNone.
318✔
2954
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
318✔
2955
                fwdPkg.ID(), decodeReqs, reforward,
318✔
2956
        )
318✔
2957
        if sphinxErr != nil {
318✔
2958
                l.failf(LinkFailureError{code: ErrInternalError},
×
2959
                        "unable to decode hop iterators: %v", sphinxErr)
×
2960
                return
×
2961
        }
×
2962

2963
        var switchPackets []*htlcPacket
318✔
2964

318✔
2965
        for i, update := range unackedAdds {
770✔
2966
                idx := uint16(i)
452✔
2967
                sourceRef := fwdPkg.SourceRef(idx)
452✔
2968
                add := *update
452✔
2969

452✔
2970
                // An incoming HTLC add has been full-locked in. As a result we
452✔
2971
                // can now examine the forwarding details of the HTLC, and the
452✔
2972
                // HTLC itself to decide if: we should forward it, cancel it,
452✔
2973
                // or are able to settle it (and it adheres to our fee related
452✔
2974
                // constraints).
452✔
2975

452✔
2976
                // Before adding the new htlc to the state machine, parse the
452✔
2977
                // onion object in order to obtain the routing information with
452✔
2978
                // DecodeHopIterator function which process the Sphinx packet.
452✔
2979
                chanIterator, failureCode := decodeResps[i].Result()
452✔
2980
                if failureCode != lnwire.CodeNone {
457✔
2981
                        // If we're unable to process the onion blob then we
5✔
2982
                        // should send the malformed htlc error to payment
5✔
2983
                        // sender.
5✔
2984
                        l.sendMalformedHTLCError(
5✔
2985
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
5✔
2986
                        )
5✔
2987

5✔
2988
                        l.log.Errorf("unable to decode onion hop iterator "+
5✔
2989
                                "for htlc(id=%v, hash=%x): %v", add.ID,
5✔
2990
                                add.PaymentHash, failureCode)
5✔
2991

5✔
2992
                        continue
5✔
2993
                }
2994

2995
                heightNow := l.cfg.BestHeight()
450✔
2996

450✔
2997
                pld, routeRole, pldErr := chanIterator.HopPayload()
450✔
2998
                if pldErr != nil {
453✔
2999
                        // If we're unable to process the onion payload, or we
3✔
3000
                        // received invalid onion payload failure, then we
3✔
3001
                        // should send an error back to the caller so the HTLC
3✔
3002
                        // can be canceled.
3✔
3003
                        var failedType uint64
3✔
3004

3✔
3005
                        // We need to get the underlying error value, so we
3✔
3006
                        // can't use errors.As as suggested by the linter.
3✔
3007
                        //nolint:errorlint
3✔
3008
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
3✔
3009
                                failedType = uint64(e.Type)
×
3010
                        }
×
3011

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

×
3029
                                // We can't process this htlc, send back
×
3030
                                // malformed.
×
3031
                                l.sendMalformedHTLCError(
×
3032
                                        add.ID, failureCode, add.OnionBlob,
×
3033
                                        &sourceRef,
×
3034
                                )
×
3035

×
3036
                                continue
×
3037
                        }
3038

3039
                        // TODO: currently none of the test unit infrastructure
3040
                        // is setup to handle TLV payloads, so testing this
3041
                        // would require implementing a separate mock iterator
3042
                        // for TLV payloads that also supports injecting invalid
3043
                        // payloads. Deferring this non-trival effort till a
3044
                        // later date
3045
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
3✔
3046

3✔
3047
                        l.sendHTLCError(
3✔
3048
                                add, sourceRef, NewLinkError(failure),
3✔
3049
                                obfuscator, false,
3✔
3050
                        )
3✔
3051

3✔
3052
                        l.log.Errorf("unable to decode forwarding "+
3✔
3053
                                "instructions: %v", pldErr)
3✔
3054

3✔
3055
                        continue
3✔
3056
                }
3057

3058
                // Retrieve onion obfuscator from onion blob in order to
3059
                // produce initial obfuscation of the onion failureCode.
3060
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
450✔
3061
                        l.cfg.ExtractErrorEncrypter,
450✔
3062
                        routeRole == hop.RouteRoleIntroduction,
450✔
3063
                )
450✔
3064
                if failureCode != lnwire.CodeNone {
451✔
3065
                        // If we're unable to process the onion blob than we
1✔
3066
                        // should send the malformed htlc error to payment
1✔
3067
                        // sender.
1✔
3068
                        l.sendMalformedHTLCError(
1✔
3069
                                add.ID, failureCode, add.OnionBlob,
1✔
3070
                                &sourceRef,
1✔
3071
                        )
1✔
3072

1✔
3073
                        l.log.Errorf("unable to decode onion "+
1✔
3074
                                "obfuscator: %v", failureCode)
1✔
3075

1✔
3076
                        continue
1✔
3077
                }
3078

3079
                fwdInfo := pld.ForwardingInfo()
449✔
3080

449✔
3081
                // Check whether the payload we've just processed uses our
449✔
3082
                // node as the introduction point (gave us a blinding key in
449✔
3083
                // the payload itself) and fail it back if we don't support
449✔
3084
                // route blinding.
449✔
3085
                if fwdInfo.NextBlinding.IsSome() &&
449✔
3086
                        l.cfg.DisallowRouteBlinding {
452✔
3087

3✔
3088
                        failure := lnwire.NewInvalidBlinding(
3✔
3089
                                fn.Some(add.OnionBlob),
3✔
3090
                        )
3✔
3091

3✔
3092
                        l.sendHTLCError(
3✔
3093
                                add, sourceRef, NewLinkError(failure),
3✔
3094
                                obfuscator, false,
3✔
3095
                        )
3✔
3096

3✔
3097
                        l.log.Error("rejected htlc that uses use as an " +
3✔
3098
                                "introduction point when we do not support " +
3✔
3099
                                "route blinding")
3✔
3100

3✔
3101
                        continue
3✔
3102
                }
3103

3104
                switch fwdInfo.NextHop {
449✔
3105
                case hop.Exit:
413✔
3106
                        err := l.processExitHop(
413✔
3107
                                add, sourceRef, obfuscator, fwdInfo,
413✔
3108
                                heightNow, pld,
413✔
3109
                        )
413✔
3110
                        if err != nil {
413✔
3111
                                l.failf(LinkFailureError{
×
3112
                                        code: ErrInternalError,
×
3113
                                }, err.Error()) //nolint
×
3114

×
3115
                                return
×
3116
                        }
×
3117

3118
                // There are additional channels left within this route. So
3119
                // we'll simply do some forwarding package book-keeping.
3120
                default:
39✔
3121
                        // If hodl.AddIncoming is requested, we will not
39✔
3122
                        // validate the forwarded ADD, nor will we send the
39✔
3123
                        // packet to the htlc switch.
39✔
3124
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
39✔
3125
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3126
                                continue
×
3127
                        }
3128

3129
                        endorseValue := l.experimentalEndorsement(
39✔
3130
                                record.CustomSet(add.CustomRecords),
39✔
3131
                        )
39✔
3132
                        endorseType := uint64(
39✔
3133
                                lnwire.ExperimentalEndorsementType,
39✔
3134
                        )
39✔
3135

39✔
3136
                        switch fwdPkg.State {
39✔
3137
                        case channeldb.FwdStateProcessed:
3✔
3138
                                // This add was not forwarded on the previous
3✔
3139
                                // processing phase, run it through our
3✔
3140
                                // validation pipeline to reproduce an error.
3✔
3141
                                // This may trigger a different error due to
3✔
3142
                                // expiring timelocks, but we expect that an
3✔
3143
                                // error will be reproduced.
3✔
3144
                                if !fwdPkg.FwdFilter.Contains(idx) {
3✔
3145
                                        break
×
3146
                                }
3147

3148
                                // Otherwise, it was already processed, we can
3149
                                // can collect it and continue.
3150
                                outgoingAdd := &lnwire.UpdateAddHTLC{
3✔
3151
                                        Expiry:        fwdInfo.OutgoingCTLV,
3✔
3152
                                        Amount:        fwdInfo.AmountToForward,
3✔
3153
                                        PaymentHash:   add.PaymentHash,
3✔
3154
                                        BlindingPoint: fwdInfo.NextBlinding,
3✔
3155
                                }
3✔
3156

3✔
3157
                                endorseValue.WhenSome(func(e byte) {
6✔
3158
                                        custRecords := map[uint64][]byte{
3✔
3159
                                                endorseType: {e},
3✔
3160
                                        }
3✔
3161

3✔
3162
                                        outgoingAdd.CustomRecords = custRecords
3✔
3163
                                })
3✔
3164

3165
                                // Finally, we'll encode the onion packet for
3166
                                // the _next_ hop using the hop iterator
3167
                                // decoded for the current hop.
3168
                                buf := bytes.NewBuffer(
3✔
3169
                                        outgoingAdd.OnionBlob[0:0],
3✔
3170
                                )
3✔
3171

3✔
3172
                                // We know this cannot fail, as this ADD
3✔
3173
                                // was marked forwarded in a previous
3✔
3174
                                // round of processing.
3✔
3175
                                chanIterator.EncodeNextHop(buf)
3✔
3176

3✔
3177
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
3178

3✔
3179
                                //nolint:ll
3✔
3180
                                updatePacket := &htlcPacket{
3✔
3181
                                        incomingChanID:       l.ShortChanID(),
3✔
3182
                                        incomingHTLCID:       add.ID,
3✔
3183
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
3184
                                        sourceRef:            &sourceRef,
3✔
3185
                                        incomingAmount:       add.Amount,
3✔
3186
                                        amount:               outgoingAdd.Amount,
3✔
3187
                                        htlc:                 outgoingAdd,
3✔
3188
                                        obfuscator:           obfuscator,
3✔
3189
                                        incomingTimeout:      add.Expiry,
3✔
3190
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
3191
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
3192
                                        inboundFee:           inboundFee,
3✔
3193
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
3194
                                }
3✔
3195
                                switchPackets = append(
3✔
3196
                                        switchPackets, updatePacket,
3✔
3197
                                )
3✔
3198

3✔
3199
                                continue
3✔
3200
                        }
3201

3202
                        // TODO(roasbeef): ensure don't accept outrageous
3203
                        // timeout for htlc
3204

3205
                        // With all our forwarding constraints met, we'll
3206
                        // create the outgoing HTLC using the parameters as
3207
                        // specified in the forwarding info.
3208
                        addMsg := &lnwire.UpdateAddHTLC{
39✔
3209
                                Expiry:        fwdInfo.OutgoingCTLV,
39✔
3210
                                Amount:        fwdInfo.AmountToForward,
39✔
3211
                                PaymentHash:   add.PaymentHash,
39✔
3212
                                BlindingPoint: fwdInfo.NextBlinding,
39✔
3213
                        }
39✔
3214

39✔
3215
                        endorseValue.WhenSome(func(e byte) {
78✔
3216
                                addMsg.CustomRecords = map[uint64][]byte{
39✔
3217
                                        endorseType: {e},
39✔
3218
                                }
39✔
3219
                        })
39✔
3220

3221
                        // Finally, we'll encode the onion packet for the
3222
                        // _next_ hop using the hop iterator decoded for the
3223
                        // current hop.
3224
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
39✔
3225
                        err := chanIterator.EncodeNextHop(buf)
39✔
3226
                        if err != nil {
39✔
3227
                                l.log.Errorf("unable to encode the "+
×
3228
                                        "remaining route %v", err)
×
3229

×
3230
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
3231
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
3232
                                }
×
3233

3234
                                failure := l.createFailureWithUpdate(
×
3235
                                        true, hop.Source, cb,
×
3236
                                )
×
3237

×
3238
                                l.sendHTLCError(
×
3239
                                        add, sourceRef, NewLinkError(failure),
×
3240
                                        obfuscator, false,
×
3241
                                )
×
3242
                                continue
×
3243
                        }
3244

3245
                        // Now that this add has been reprocessed, only append
3246
                        // it to our list of packets to forward to the switch
3247
                        // this is the first time processing the add. If the
3248
                        // fwd pkg has already been processed, then we entered
3249
                        // the above section to recreate a previous error.  If
3250
                        // the packet had previously been forwarded, it would
3251
                        // have been added to switchPackets at the top of this
3252
                        // section.
3253
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
78✔
3254
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
39✔
3255

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

39✔
3273
                                fwdPkg.FwdFilter.Set(idx)
39✔
3274
                                switchPackets = append(switchPackets,
39✔
3275
                                        updatePacket)
39✔
3276
                        }
39✔
3277
                }
3278
        }
3279

3280
        // Commit the htlcs we are intending to forward if this package has not
3281
        // been fully processed.
3282
        if fwdPkg.State == channeldb.FwdStateLockedIn {
633✔
3283
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
315✔
3284
                if err != nil {
315✔
3285
                        l.failf(LinkFailureError{code: ErrInternalError},
×
3286
                                "unable to set fwd filter: %v", err)
×
3287
                        return
×
3288
                }
×
3289
        }
3290

3291
        if len(switchPackets) == 0 {
600✔
3292
                return
282✔
3293
        }
282✔
3294

3295
        l.log.Debugf("forwarding %d packets to switch: reforward=%v",
39✔
3296
                len(switchPackets), reforward)
39✔
3297

39✔
3298
        // NOTE: This call is made synchronous so that we ensure all circuits
39✔
3299
        // are committed in the exact order that they are processed in the link.
39✔
3300
        // Failing to do this could cause reorderings/gaps in the range of
39✔
3301
        // opened circuits, which violates assumptions made by the circuit
39✔
3302
        // trimming.
39✔
3303
        l.forwardBatch(reforward, switchPackets...)
39✔
3304
}
3305

3306
// experimentalEndorsement returns the value to set for our outgoing
3307
// experimental endorsement field, and a boolean indicating whether it should
3308
// be populated on the outgoing htlc.
3309
func (l *channelLink) experimentalEndorsement(
3310
        customUpdateAdd record.CustomSet) fn.Option[byte] {
39✔
3311

39✔
3312
        // Only relay experimental signal if we are within the experiment
39✔
3313
        // period.
39✔
3314
        if !l.cfg.ShouldFwdExpEndorsement() {
42✔
3315
                return fn.None[byte]()
3✔
3316
        }
3✔
3317

3318
        // If we don't have any custom records or the experimental field is
3319
        // not set, just forward a zero value.
3320
        if len(customUpdateAdd) == 0 {
78✔
3321
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
39✔
3322
        }
39✔
3323

3324
        t := uint64(lnwire.ExperimentalEndorsementType)
3✔
3325
        value, set := customUpdateAdd[t]
3✔
3326
        if !set {
3✔
3327
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
3328
        }
×
3329

3330
        // We expect at least one byte for this field, consider it invalid if
3331
        // it has no data and just forward a zero value.
3332
        if len(value) == 0 {
3✔
3333
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
3334
        }
×
3335

3336
        // Only forward endorsed if the incoming link is endorsed.
3337
        if value[0] == lnwire.ExperimentalEndorsed {
6✔
3338
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
3✔
3339
        }
3✔
3340

3341
        // Forward as unendorsed otherwise, including cases where we've
3342
        // received an invalid value that uses more than 3 bits of information.
3343
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
3344
}
3345

3346
// processExitHop handles an htlc for which this link is the exit hop. It
3347
// returns a boolean indicating whether the commitment tx needs an update.
3348
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
3349
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
3350
        fwdInfo hop.ForwardingInfo, heightNow uint32,
3351
        payload invoices.Payload) error {
413✔
3352

413✔
3353
        // If hodl.ExitSettle is requested, we will not validate the final hop's
413✔
3354
        // ADD, nor will we settle the corresponding invoice or respond with the
413✔
3355
        // preimage.
413✔
3356
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
523✔
3357
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
110✔
3358
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
110✔
3359

110✔
3360
                return nil
110✔
3361
        }
110✔
3362

3363
        // In case the traffic shaper is active, we'll check if the HTLC has
3364
        // custom records and skip the amount check in the onion payload below.
3365
        isCustomHTLC := fn.MapOptionZ(
306✔
3366
                l.cfg.AuxTrafficShaper,
306✔
3367
                func(ts AuxTrafficShaper) bool {
306✔
3368
                        return ts.IsCustomHTLC(add.CustomRecords)
×
3369
                },
×
3370
        )
3371

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

100✔
3381
                failure := NewLinkError(
100✔
3382
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
100✔
3383
                )
100✔
3384
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
100✔
3385

100✔
3386
                return nil
100✔
3387
        }
100✔
3388

3389
        // We'll also ensure that our time-lock value has been computed
3390
        // correctly.
3391
        if add.Expiry < fwdInfo.OutgoingCTLV {
207✔
3392
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
1✔
3393
                        "incompatible time-lock: expected <=%v, got %v",
1✔
3394
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
1✔
3395

1✔
3396
                failure := NewLinkError(
1✔
3397
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
1✔
3398
                )
1✔
3399

1✔
3400
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
1✔
3401

1✔
3402
                return nil
1✔
3403
        }
1✔
3404

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

205✔
3410
        circuitKey := models.CircuitKey{
205✔
3411
                ChanID: l.ShortChanID(),
205✔
3412
                HtlcID: add.ID,
205✔
3413
        }
205✔
3414

205✔
3415
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
205✔
3416
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
205✔
3417
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
205✔
3418
        )
205✔
3419
        if err != nil {
205✔
3420
                return err
×
3421
        }
×
3422

3423
        // Create a hodlHtlc struct and decide either resolved now or later.
3424
        htlc := hodlHtlc{
205✔
3425
                add:        add,
205✔
3426
                sourceRef:  sourceRef,
205✔
3427
                obfuscator: obfuscator,
205✔
3428
        }
205✔
3429

205✔
3430
        // If the event is nil, the invoice is being held, so we save payment
205✔
3431
        // descriptor for future reference.
205✔
3432
        if event == nil {
264✔
3433
                l.hodlMap[circuitKey] = htlc
59✔
3434
                return nil
59✔
3435
        }
59✔
3436

3437
        // Process the received resolution.
3438
        return l.processHtlcResolution(event, htlc)
149✔
3439
}
3440

3441
// settleHTLC settles the HTLC on the channel.
3442
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
3443
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
200✔
3444

200✔
3445
        hash := preimage.Hash()
200✔
3446

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

200✔
3449
        err := l.channel.SettleHTLC(
200✔
3450
                preimage, htlcIndex, &sourceRef, nil, nil,
200✔
3451
        )
200✔
3452
        if err != nil {
200✔
3453
                return fmt.Errorf("unable to settle htlc: %w", err)
×
3454
        }
×
3455

3456
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
3457
        // fake one before sending it to the peer.
3458
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
203✔
3459
                l.log.Warnf(hodl.BogusSettle.Warning())
3✔
3460
                preimage = [32]byte{}
3✔
3461
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
3✔
3462
        }
3✔
3463

3464
        // HTLC was successfully settled locally send notification about it
3465
        // remote peer.
3466
        err = l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
200✔
3467
                ChanID:          l.ChanID(),
200✔
3468
                ID:              htlcIndex,
200✔
3469
                PaymentPreimage: preimage,
200✔
3470
        })
200✔
3471
        if err != nil {
200✔
NEW
3472
                l.log.Errorf("failed to send UpdateFulfillHTLC: %v", err)
×
NEW
3473
        }
×
3474

3475
        // Once we have successfully settled the htlc, notify a settle event.
3476
        l.cfg.HtlcNotifier.NotifySettleEvent(
200✔
3477
                HtlcKey{
200✔
3478
                        IncomingCircuit: models.CircuitKey{
200✔
3479
                                ChanID: l.ShortChanID(),
200✔
3480
                                HtlcID: htlcIndex,
200✔
3481
                        },
200✔
3482
                },
200✔
3483
                preimage,
200✔
3484
                HtlcEventTypeReceive,
200✔
3485
        )
200✔
3486

200✔
3487
        return nil
200✔
3488
}
3489

3490
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
3491
// err chan for the individual responses. This method is intended to be spawned
3492
// as a goroutine so the responses can be handled in the background.
3493
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
579✔
3494
        // Don't forward packets for which we already have a response in our
579✔
3495
        // mailbox. This could happen if a packet fails and is buffered in the
579✔
3496
        // mailbox, and the incoming link flaps.
579✔
3497
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
579✔
3498
        for _, pkt := range packets {
1,158✔
3499
                if l.mailBox.HasPacket(pkt.inKey()) {
582✔
3500
                        continue
3✔
3501
                }
3502

3503
                filteredPkts = append(filteredPkts, pkt)
579✔
3504
        }
3505

3506
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
579✔
3507
        if err != nil {
590✔
3508
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
3509
                        "settle/fail over htlcswitch: %v", err)
11✔
3510
        }
11✔
3511
}
3512

3513
// sendHTLCError functions cancels HTLC and send cancel message back to the
3514
// peer from which HTLC was received.
3515
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
3516
        sourceRef channeldb.AddRef, failure *LinkError,
3517
        e hop.ErrorEncrypter, isReceive bool) {
108✔
3518

108✔
3519
        reason, err := e.EncryptFirstHop(failure.WireMessage())
108✔
3520
        if err != nil {
108✔
3521
                l.log.Errorf("unable to obfuscate error: %v", err)
×
3522
                return
×
3523
        }
×
3524

3525
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
108✔
3526
        if err != nil {
108✔
3527
                l.log.Errorf("unable cancel htlc: %v", err)
×
3528
                return
×
3529
        }
×
3530

3531
        // Send the appropriate failure message depending on whether we're
3532
        // in a blinded route or not.
3533
        if err := l.sendIncomingHTLCFailureMsg(
108✔
3534
                add.ID, e, reason,
108✔
3535
        ); err != nil {
108✔
3536
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
3537
                return
×
3538
        }
×
3539

3540
        // Notify a link failure on our incoming link. Outgoing htlc information
3541
        // is not available at this point, because we have not decrypted the
3542
        // onion, so it is excluded.
3543
        var eventType HtlcEventType
108✔
3544
        if isReceive {
216✔
3545
                eventType = HtlcEventTypeReceive
108✔
3546
        } else {
111✔
3547
                eventType = HtlcEventTypeForward
3✔
3548
        }
3✔
3549

3550
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
108✔
3551
                HtlcKey{
108✔
3552
                        IncomingCircuit: models.CircuitKey{
108✔
3553
                                ChanID: l.ShortChanID(),
108✔
3554
                                HtlcID: add.ID,
108✔
3555
                        },
108✔
3556
                },
108✔
3557
                HtlcInfo{
108✔
3558
                        IncomingTimeLock: add.Expiry,
108✔
3559
                        IncomingAmt:      add.Amount,
108✔
3560
                },
108✔
3561
                eventType,
108✔
3562
                failure,
108✔
3563
                true,
108✔
3564
        )
108✔
3565
}
3566

3567
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
3568
// peer from which the HTLC was received. This function is primarily used to
3569
// handle the special requirements of route blinding, specifically:
3570
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
3571
// - Introduction nodes should return regular HTLC failure messages.
3572
//
3573
// It accepts the original opaque failure, which will be used in the case
3574
// that we're not part of a blinded route and an error encrypter that'll be
3575
// used if we are the introduction node and need to present an error as if
3576
// we're the failing party.
3577
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
3578
        e hop.ErrorEncrypter,
3579
        originalFailure lnwire.OpaqueReason) error {
124✔
3580

124✔
3581
        var msg lnwire.Message
124✔
3582
        switch {
124✔
3583
        // Our circuit's error encrypter will be nil if this was a locally
3584
        // initiated payment. We can only hit a blinded error for a locally
3585
        // initiated payment if we allow ourselves to be picked as the
3586
        // introduction node for our own payments and in that case we
3587
        // shouldn't reach this code. To prevent the HTLC getting stuck,
3588
        // we fail it back and log an error.
3589
        // code.
3590
        case e == nil:
×
3591
                msg = &lnwire.UpdateFailHTLC{
×
3592
                        ChanID: l.ChanID(),
×
3593
                        ID:     htlcIndex,
×
3594
                        Reason: originalFailure,
×
3595
                }
×
3596

×
3597
                l.log.Errorf("Unexpected blinded failure when "+
×
3598
                        "we are the sending node, incoming htlc: %v(%v)",
×
3599
                        l.ShortChanID(), htlcIndex)
×
3600

3601
        // For cleartext hops (ie, non-blinded/normal) we don't need any
3602
        // transformation on the error message and can just send the original.
3603
        case !e.Type().IsBlinded():
124✔
3604
                msg = &lnwire.UpdateFailHTLC{
124✔
3605
                        ChanID: l.ChanID(),
124✔
3606
                        ID:     htlcIndex,
124✔
3607
                        Reason: originalFailure,
124✔
3608
                }
124✔
3609

3610
        // When we're the introduction node, we need to convert the error to
3611
        // a UpdateFailHTLC.
3612
        case e.Type() == hop.EncrypterTypeIntroduction:
3✔
3613
                l.log.Debugf("Introduction blinded node switching out failure "+
3✔
3614
                        "error: %v", htlcIndex)
3✔
3615

3✔
3616
                // The specification does not require that we set the onion
3✔
3617
                // blob.
3✔
3618
                failureMsg := lnwire.NewInvalidBlinding(
3✔
3619
                        fn.None[[lnwire.OnionPacketSize]byte](),
3✔
3620
                )
3✔
3621
                reason, err := e.EncryptFirstHop(failureMsg)
3✔
3622
                if err != nil {
3✔
3623
                        return err
×
3624
                }
×
3625

3626
                msg = &lnwire.UpdateFailHTLC{
3✔
3627
                        ChanID: l.ChanID(),
3✔
3628
                        ID:     htlcIndex,
3✔
3629
                        Reason: reason,
3✔
3630
                }
3✔
3631

3632
        // If we are a relaying node, we need to switch out any error that
3633
        // we've received to a malformed HTLC error.
3634
        case e.Type() == hop.EncrypterTypeRelaying:
3✔
3635
                l.log.Debugf("Relaying blinded node switching out malformed "+
3✔
3636
                        "error: %v", htlcIndex)
3✔
3637

3✔
3638
                msg = &lnwire.UpdateFailMalformedHTLC{
3✔
3639
                        ChanID:      l.ChanID(),
3✔
3640
                        ID:          htlcIndex,
3✔
3641
                        FailureCode: lnwire.CodeInvalidBlinding,
3✔
3642
                }
3✔
3643

3644
        default:
×
3645
                return fmt.Errorf("unexpected encrypter: %d", e)
×
3646
        }
3647

3648
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
124✔
3649
                l.log.Warnf("Send update fail failed: %v", err)
×
3650
        }
×
3651

3652
        return nil
124✔
3653
}
3654

3655
// sendMalformedHTLCError helper function which sends the malformed HTLC update
3656
// to the payment sender.
3657
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
3658
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
3659
        sourceRef *channeldb.AddRef) {
6✔
3660

6✔
3661
        shaOnionBlob := sha256.Sum256(onionBlob[:])
6✔
3662
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
6✔
3663
        if err != nil {
6✔
3664
                l.log.Errorf("unable cancel htlc: %v", err)
×
3665
                return
×
3666
        }
×
3667

3668
        err = l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
6✔
3669
                ChanID:       l.ChanID(),
6✔
3670
                ID:           htlcIndex,
6✔
3671
                ShaOnionBlob: shaOnionBlob,
6✔
3672
                FailureCode:  code,
6✔
3673
        })
6✔
3674
        if err != nil {
6✔
NEW
3675
                l.log.Errorf("failed to send UpdateFailMalformedHTLC: %v", err)
×
NEW
3676
        }
×
3677
}
3678

3679
// failf is a function which is used to encapsulate the action necessary for
3680
// properly failing the link. It takes a LinkFailureError, which will be passed
3681
// to the OnChannelFailure closure, in order for it to determine if we should
3682
// force close the channel, and if we should send an error message to the
3683
// remote peer.
3684
func (l *channelLink) failf(linkErr LinkFailureError, format string,
3685
        a ...interface{}) {
18✔
3686

18✔
3687
        reason := fmt.Errorf(format, a...)
18✔
3688

18✔
3689
        // Return if we have already notified about a failure.
18✔
3690
        if l.failed {
21✔
3691
                l.log.Warnf("ignoring link failure (%v), as link already "+
3✔
3692
                        "failed", reason)
3✔
3693
                return
3✔
3694
        }
3✔
3695

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

18✔
3698
        // Set failed, such that we won't process any more updates, and notify
18✔
3699
        // the peer about the failure.
18✔
3700
        l.failed = true
18✔
3701
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
18✔
3702
}
3703

3704
// FundingCustomBlob returns the custom funding blob of the channel that this
3705
// link is associated with. The funding blob represents static information about
3706
// the channel that was created at channel funding time.
3707
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
3708
        if l.channel == nil {
×
3709
                return fn.None[tlv.Blob]()
×
3710
        }
×
3711

3712
        if l.channel.State() == nil {
×
3713
                return fn.None[tlv.Blob]()
×
3714
        }
×
3715

3716
        return l.channel.State().CustomBlob
×
3717
}
3718

3719
// CommitmentCustomBlob returns the custom blob of the current local commitment
3720
// of the channel that this link is associated with.
3721
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
3722
        if l.channel == nil {
×
3723
                return fn.None[tlv.Blob]()
×
3724
        }
×
3725

3726
        return l.channel.LocalCommitmentBlob()
×
3727
}
3728

3729
// handleHtlcResolution takes an HTLC resolution and processes it by draining
3730
// the hodlQueue. Once processed, a commit_sig is sent to the remote to update
3731
// their commitment.
3732
func (l *channelLink) handleHtlcResolution(ctx context.Context, hodlItem any) {
58✔
3733
        htlcResolution, ok := hodlItem.(invoices.HtlcResolution)
58✔
3734
        if !ok {
58✔
NEW
3735
                l.log.Errorf("expect HtlcResolution, got %T", hodlItem)
×
NEW
3736
                return
×
NEW
3737
        }
×
3738

3739
        err := l.processHodlQueue(ctx, htlcResolution)
58✔
3740
        switch {
58✔
3741
        // No error, success.
3742
        case err == nil:
57✔
3743

3744
        // If the duplicate keystone error was encountered, fail back
3745
        // gracefully.
NEW
3746
        case errors.Is(err, ErrDuplicateKeystone):
×
NEW
3747
                l.failf(
×
NEW
3748
                        LinkFailureError{
×
NEW
3749
                                code: ErrCircuitError,
×
NEW
3750
                        },
×
NEW
3751
                        "process hodl queue: temporary circuit error: %v", err,
×
NEW
3752
                )
×
3753

3754
        // Send an Error message to the peer.
3755
        default:
1✔
3756
                l.failf(
1✔
3757
                        LinkFailureError{
1✔
3758
                                code: ErrInternalError,
1✔
3759
                        },
1✔
3760
                        "process hodl queue: unable to update commitment: %v",
1✔
3761
                        err,
1✔
3762
                )
1✔
3763
        }
3764
}
3765

3766
// handleQuiescenceReq takes a locally initialized (RPC) quiescence request and
3767
// forwards it to the quiescer for further processing.
3768
func (l *channelLink) handleQuiescenceReq(req StfuReq) {
4✔
3769
        l.quiescer.InitStfu(req)
4✔
3770

4✔
3771
        if l.noDanglingUpdates(lntypes.Local) {
8✔
3772
                err := l.quiescer.SendOwedStfu()
4✔
3773
                if err != nil {
4✔
NEW
3774
                        l.stfuFailf("SendOwedStfu: %s", err.Error())
×
NEW
3775
                        res := fn.Err[lntypes.ChannelParty](err)
×
NEW
3776
                        req.Resolve(res)
×
NEW
3777
                }
×
3778
        }
3779
}
3780

3781
// handleUpdateFee is called whenever the `updateFeeTimer` ticks. It is used to
3782
// decide whether we should send an `update_fee` msg to update the commitment's
3783
// feerate.
3784
func (l *channelLink) handleUpdateFee(ctx context.Context) {
4✔
3785
        // If we're not the initiator of the channel, we don't control the fees,
4✔
3786
        // so we can ignore this.
4✔
3787
        if !l.channel.IsInitiator() {
4✔
NEW
3788
                return
×
NEW
3789
        }
×
3790

3791
        // If we are the initiator, then we'll sample the current fee rate to
3792
        // get into the chain within 3 blocks.
3793
        netFee, err := l.sampleNetworkFee()
4✔
3794
        if err != nil {
4✔
NEW
3795
                l.log.Errorf("unable to sample network fee: %v", err)
×
NEW
3796

×
NEW
3797
                return
×
NEW
3798
        }
×
3799

3800
        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
4✔
3801

4✔
3802
        newCommitFee := l.channel.IdealCommitFeeRate(
4✔
3803
                netFee, minRelayFee,
4✔
3804
                l.cfg.MaxAnchorsCommitFeeRate,
4✔
3805
                l.cfg.MaxFeeAllocation,
4✔
3806
        )
4✔
3807

4✔
3808
        // We determine if we should adjust the commitment fee based on the
4✔
3809
        // current commitment fee, the suggested new commitment fee and the
4✔
3810
        // current minimum relay fee rate.
4✔
3811
        commitFee := l.channel.CommitFeeRate()
4✔
3812
        if !shouldAdjustCommitFee(newCommitFee, commitFee, minRelayFee) {
5✔
3813
                return
1✔
3814
        }
1✔
3815

3816
        // If we do, then we'll send a new UpdateFee message to the remote
3817
        // party, to be locked in with a new update.
3818
        err = l.updateChannelFee(ctx, newCommitFee)
3✔
3819
        if err != nil {
3✔
NEW
3820
                l.log.Errorf("unable to update fee rate: %v", err)
×
NEW
3821
        }
×
3822
}
3823

3824
// toggleBatchTicker checks whether we need to resume or pause the batch ticker.
3825
// When we have no pending updates, the ticker is paused, otherwise resumed.
3826
func (l *channelLink) toggleBatchTicker() {
4,167✔
3827
        // If the previous event resulted in a non-empty batch, resume the batch
4,167✔
3828
        // ticker so that it can be cleared. Otherwise pause the ticker to
4,167✔
3829
        // prevent waking up the htlcManager while the batch is empty.
4,167✔
3830
        numUpdates := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
4,167✔
3831
        if numUpdates > 0 {
4,670✔
3832
                l.cfg.BatchTicker.Resume()
503✔
3833
                l.log.Tracef("BatchTicker resumed, NumPendingUpdates(Local, "+
503✔
3834
                        "Remote)=%d", numUpdates)
503✔
3835
        } else {
4,170✔
3836
                l.cfg.BatchTicker.Pause()
3,667✔
3837
                l.log.Trace("BatchTicker paused due to zero NumPendingUpdates" +
3,667✔
3838
                        "(Local, Remote)")
3,667✔
3839
        }
3,667✔
3840
}
3841

3842
// resumeLink is called when starting a previous link. It will go through the
3843
// reestablishment protocol and reforwarding packets that are yet resolved.
3844
func (l *channelLink) resumeLink(ctx context.Context) {
216✔
3845
        // If this isn't the first time that this channel link has been created,
216✔
3846
        // then we'll need to check to see if we need to re-synchronize state
216✔
3847
        // with the remote peer. settledHtlcs is a map of HTLC's that we
216✔
3848
        // re-settled as part of the channel state sync.
216✔
3849
        if l.cfg.SyncStates {
389✔
3850
                err := l.syncChanStates(ctx)
173✔
3851
                if err != nil {
176✔
3852
                        l.handleChanSyncErr(err)
3✔
3853
                        return
3✔
3854
                }
3✔
3855
        }
3856

3857
        // If a shutdown message has previously been sent on this link, then we
3858
        // need to make sure that we have disabled any HTLC adds on the outgoing
3859
        // direction of the link and that we re-resend the same shutdown message
3860
        // that we previously sent.
3861
        //
3862
        // TODO(yy): we should either move this to chanCloser, or move all
3863
        // shutdown handling logic to be managed by the link, but not a mixed of
3864
        // partial management by two subsystems.
3865
        l.cfg.PreviouslySentShutdown.WhenSome(func(shutdown lnwire.Shutdown) {
219✔
3866
                // Immediately disallow any new outgoing HTLCs.
3✔
3867
                if !l.DisableAdds(Outgoing) {
3✔
NEW
3868
                        l.log.Warnf("Outgoing link adds already disabled")
×
NEW
3869
                }
×
3870

3871
                // Re-send the shutdown message the peer. Since syncChanStates
3872
                // would have sent any outstanding CommitSig, it is fine for us
3873
                // to immediately queue the shutdown message now.
3874
                err := l.cfg.Peer.SendMessage(false, &shutdown)
3✔
3875
                if err != nil {
3✔
NEW
3876
                        l.log.Warnf("Error sending shutdown message: %v", err)
×
NEW
3877
                }
×
3878
        })
3879

3880
        // We've successfully reestablished the channel, mark it as such to
3881
        // allow the switch to forward HTLCs in the outbound direction.
3882
        l.markReestablished()
216✔
3883

216✔
3884
        // With the channel states synced, we now reset the mailbox to ensure we
216✔
3885
        // start processing all unacked packets in order. This is done here to
216✔
3886
        // ensure that all acknowledgments that occur during channel
216✔
3887
        // resynchronization have taken affect, causing us only to pull unacked
216✔
3888
        // packets after starting to read from the downstream mailbox.
216✔
3889
        err := l.mailBox.ResetPackets()
216✔
3890
        if err != nil {
216✔
NEW
3891
                l.log.Errorf("failed to reset packets: %v", err)
×
NEW
3892
        }
×
3893

3894
        // After cleaning up any memory pertaining to incoming packets, we now
3895
        // replay our forwarding packages to handle any htlcs that can be
3896
        // processed locally, or need to be forwarded out to the switch. We will
3897
        // only attempt to resolve packages if our short chan id indicates that
3898
        // the channel is not pending, otherwise we should have no htlcs to
3899
        // reforward.
3900
        if l.ShortChanID() != hop.Source {
432✔
3901
                err := l.resolveFwdPkgs(ctx)
216✔
3902
                switch {
216✔
3903
                // No error was encountered, success.
3904
                case err == nil:
215✔
3905

3906
                // If the duplicate keystone error was encountered, we'll fail
3907
                // without sending an Error message to the peer.
NEW
3908
                case errors.Is(err, ErrDuplicateKeystone):
×
NEW
3909
                        l.failf(LinkFailureError{code: ErrCircuitError},
×
NEW
3910
                                "temporary circuit error: %v", err)
×
NEW
3911
                        return
×
3912

3913
                // A non-nil error was encountered, send an Error message to the
3914
                // peer.
3915
                default:
1✔
3916
                        l.failf(LinkFailureError{code: ErrInternalError},
1✔
3917
                                "unable to resolve fwd pkgs: %v", err)
1✔
3918
                        return
1✔
3919
                }
3920

3921
                // With our link's in-memory state fully reconstructed, spawn a
3922
                // goroutine to manage the reclamation of disk space occupied by
3923
                // completed forwarding packages.
3924
                l.cg.WgAdd(1)
215✔
3925
                go l.fwdPkgGarbager()
215✔
3926
        }
3927
}
3928

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

×
NEW
3961
                return
×
NEW
3962
        }
×
3963

3964
        // Disallow htlcs with blinding points set if we haven't enabled the
3965
        // feature. This saves us from having to process the onion at all, but
3966
        // will only catch blinded payments where we are a relaying node (as the
3967
        // blinding point will be in the payload when we're the introduction
3968
        // node).
3969
        if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
453✔
NEW
3970
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
3971
                        "blinding point included when route blinding "+
×
NEW
3972
                                "is disabled")
×
NEW
3973

×
NEW
3974
                return
×
NEW
3975
        }
×
3976

3977
        // We have to check the limit here rather than later in the switch
3978
        // because the counterparty can keep sending HTLC's without sending a
3979
        // revoke. This would mean that the switch check would only occur later.
3980
        if l.isOverexposedWithHtlc(msg, true) {
453✔
NEW
3981
                l.failf(LinkFailureError{code: ErrInternalError},
×
NEW
3982
                        "peer sent us an HTLC that exceeded our max "+
×
NEW
3983
                                "fee exposure")
×
NEW
3984

×
NEW
3985
                return
×
NEW
3986
        }
×
3987

3988
        // We just received an add request from an upstream peer, so we add it
3989
        // to our state machine, then add the HTLC to our "settle" list in the
3990
        // event that we know the preimage.
3991
        index, err := l.channel.ReceiveHTLC(msg)
453✔
3992
        if err != nil {
453✔
NEW
3993
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
3994
                        "unable to handle upstream add HTLC: %v", err)
×
NEW
3995
                return
×
NEW
3996
        }
×
3997

3998
        l.log.Tracef("receive upstream htlc with payment hash(%x), "+
453✔
3999
                "assigning index: %v", msg.PaymentHash[:], index)
453✔
4000
}
4001

4002
// processRemoteUpdateFulfillHTLC takes an `UpdateFulfillHTLC` msg sent from the
4003
// remote and processes it.
4004
func (l *channelLink) processRemoteUpdateFulfillHTLC(
4005
        msg *lnwire.UpdateFulfillHTLC) {
230✔
4006

230✔
4007
        pre := msg.PaymentPreimage
230✔
4008
        idx := msg.ID
230✔
4009

230✔
4010
        // Before we pipeline the settle, we'll check the set of active htlc's
230✔
4011
        // to see if the related UpdateAddHTLC has been fully locked-in.
230✔
4012
        var lockedin bool
230✔
4013
        htlcs := l.channel.ActiveHtlcs()
230✔
4014
        for _, add := range htlcs {
655✔
4015
                // The HTLC will be outgoing and match idx.
425✔
4016
                if !add.Incoming && add.HtlcIndex == idx {
653✔
4017
                        lockedin = true
228✔
4018
                        break
228✔
4019
                }
4020
        }
4021

4022
        if !lockedin {
232✔
4023
                l.failf(
2✔
4024
                        LinkFailureError{code: ErrInvalidUpdate},
2✔
4025
                        "unable to handle upstream settle",
2✔
4026
                )
2✔
4027

2✔
4028
                return
2✔
4029
        }
2✔
4030

4031
        if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
231✔
4032
                l.failf(
3✔
4033
                        LinkFailureError{
3✔
4034
                                code:          ErrInvalidUpdate,
3✔
4035
                                FailureAction: LinkFailureForceClose,
3✔
4036
                        },
3✔
4037
                        "unable to handle upstream settle HTLC: %v", err,
3✔
4038
                )
3✔
4039

3✔
4040
                return
3✔
4041
        }
3✔
4042

4043
        settlePacket := &htlcPacket{
228✔
4044
                outgoingChanID: l.ShortChanID(),
228✔
4045
                outgoingHTLCID: idx,
228✔
4046
                htlc: &lnwire.UpdateFulfillHTLC{
228✔
4047
                        PaymentPreimage: pre,
228✔
4048
                },
228✔
4049
        }
228✔
4050

228✔
4051
        // Add the newly discovered preimage to our growing list of uncommitted
228✔
4052
        // preimage. These will be written to the witness cache just before
228✔
4053
        // accepting the next commitment signature from the remote peer.
228✔
4054
        l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
228✔
4055

228✔
4056
        // Pipeline this settle, send it to the switch.
228✔
4057
        go l.forwardBatch(false, settlePacket)
228✔
4058
}
4059

4060
// processRemoteUpdateFailMalformedHTLC takes an `UpdateFailMalformedHTLC` msg
4061
// sent from the remote and processes it.
4062
func (l *channelLink) processRemoteUpdateFailMalformedHTLC(
4063
        msg *lnwire.UpdateFailMalformedHTLC) {
6✔
4064

6✔
4065
        // Convert the failure type encoded within the HTLC fail message to the
6✔
4066
        // proper generic lnwire error code.
6✔
4067
        var failure lnwire.FailureMessage
6✔
4068
        switch msg.FailureCode {
6✔
4069
        case lnwire.CodeInvalidOnionVersion:
4✔
4070
                failure = &lnwire.FailInvalidOnionVersion{
4✔
4071
                        OnionSHA256: msg.ShaOnionBlob,
4✔
4072
                }
4✔
NEW
4073
        case lnwire.CodeInvalidOnionHmac:
×
NEW
4074
                failure = &lnwire.FailInvalidOnionHmac{
×
NEW
4075
                        OnionSHA256: msg.ShaOnionBlob,
×
NEW
4076
                }
×
4077

NEW
4078
        case lnwire.CodeInvalidOnionKey:
×
NEW
4079
                failure = &lnwire.FailInvalidOnionKey{
×
NEW
4080
                        OnionSHA256: msg.ShaOnionBlob,
×
NEW
4081
                }
×
4082

4083
        // Handle malformed errors that are part of a blinded route. This case
4084
        // is slightly different, because we expect every relaying node in the
4085
        // blinded portion of the route to send malformed errors. If we're also
4086
        // a relaying node, we're likely going to switch this error out anyway
4087
        // for our own malformed error, but we handle the case here for
4088
        // completeness.
4089
        case lnwire.CodeInvalidBlinding:
3✔
4090
                failure = &lnwire.FailInvalidBlinding{
3✔
4091
                        OnionSHA256: msg.ShaOnionBlob,
3✔
4092
                }
3✔
4093

4094
        default:
2✔
4095
                l.log.Warnf("unexpected failure code received in "+
2✔
4096
                        "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
4097

2✔
4098
                // We don't just pass back the error we received from our
2✔
4099
                // successor. Otherwise we might report a failure that penalizes
2✔
4100
                // us more than needed. If the onion that we forwarded was
2✔
4101
                // correct, the node should have been able to send back its own
2✔
4102
                // failure. The node did not send back its own failure, so we
2✔
4103
                // assume there was a problem with the onion and report that
2✔
4104
                // back. We reuse the invalid onion key failure because there is
2✔
4105
                // no specific error for this case.
2✔
4106
                failure = &lnwire.FailInvalidOnionKey{
2✔
4107
                        OnionSHA256: msg.ShaOnionBlob,
2✔
4108
                }
2✔
4109
        }
4110

4111
        // With the error parsed, we'll convert the into it's opaque form.
4112
        var b bytes.Buffer
6✔
4113
        if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
6✔
NEW
4114
                l.log.Errorf("unable to encode malformed error: %v", err)
×
NEW
4115
                return
×
NEW
4116
        }
×
4117

4118
        // If remote side have been unable to parse the onion blob we have sent
4119
        // to it, than we should transform the malformed HTLC message to the
4120
        // usual HTLC fail message.
4121
        err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
6✔
4122
        if err != nil {
6✔
NEW
4123
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
4124
                        "unable to handle upstream fail HTLC: %v", err)
×
NEW
4125

×
NEW
4126
                return
×
NEW
4127
        }
×
4128
}
4129

4130
// processRemoteUpdateFailHTLC takes an `UpdateFailHTLC` msg sent from the
4131
// remote and processes it.
4132
func (l *channelLink) processRemoteUpdateFailHTLC(msg *lnwire.UpdateFailHTLC) {
123✔
4133
        // Verify that the failure reason is at least 256 bytes plus overhead.
123✔
4134
        const minimumFailReasonLength = lnwire.FailureMessageLength + 2 + 2 + 32
123✔
4135

123✔
4136
        if len(msg.Reason) < minimumFailReasonLength {
124✔
4137
                // We've received a reason with a non-compliant length. Older
1✔
4138
                // nodes happily relay back these failures that may originate
1✔
4139
                // from a node further downstream. Therefore we can't just fail
1✔
4140
                // the channel.
1✔
4141
                //
1✔
4142
                // We want to be compliant ourselves, so we also can't pass back
1✔
4143
                // the reason unmodified. And we must make sure that we don't
1✔
4144
                // hit the magic length check of 260 bytes in
1✔
4145
                // processRemoteSettleFails either.
1✔
4146
                //
1✔
4147
                // Because the reason is unreadable for the payer anyway, we
1✔
4148
                // just replace it by a compliant-length series of random bytes.
1✔
4149
                msg.Reason = make([]byte, minimumFailReasonLength)
1✔
4150
                _, err := crand.Read(msg.Reason[:])
1✔
4151
                if err != nil {
1✔
NEW
4152
                        l.log.Errorf("Random generation error: %v", err)
×
NEW
4153

×
NEW
4154
                        return
×
NEW
4155
                }
×
4156
        }
4157

4158
        // Add fail to the update log.
4159
        idx := msg.ID
123✔
4160
        err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
123✔
4161
        if err != nil {
123✔
NEW
4162
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
4163
                        "unable to handle upstream fail HTLC: %v", err)
×
NEW
4164

×
NEW
4165
                return
×
NEW
4166
        }
×
4167
}
4168

4169
// processRemoteCommitSig takes a `CommitSig` msg sent from the remote and
4170
// processes it.
4171
func (l *channelLink) processRemoteCommitSig(ctx context.Context,
4172
        msg *lnwire.CommitSig) {
1,198✔
4173

1,198✔
4174
        // Since we may have learned new preimages for the first time, we'll add
1,198✔
4175
        // them to our preimage cache. By doing this, we ensure any contested
1,198✔
4176
        // contracts watched by any on-chain arbitrators can now sweep this HTLC
1,198✔
4177
        // on-chain. We delay committing the preimages until just before
1,198✔
4178
        // accepting the new remote commitment, as afterwards the peer won't
1,198✔
4179
        // resend the Settle messages on the next channel reestablishment. Doing
1,198✔
4180
        // so allows us to more effectively batch this operation, instead of
1,198✔
4181
        // doing a single write per preimage.
1,198✔
4182
        err := l.cfg.PreimageCache.AddPreimages(l.uncommittedPreimages...)
1,198✔
4183
        if err != nil {
1,198✔
NEW
4184
                l.failf(
×
NEW
4185
                        LinkFailureError{code: ErrInternalError},
×
NEW
4186
                        "unable to add preimages=%v to cache: %v",
×
NEW
4187
                        l.uncommittedPreimages, err,
×
NEW
4188
                )
×
NEW
4189

×
NEW
4190
                return
×
NEW
4191
        }
×
4192

4193
        // Instead of truncating the slice to conserve memory allocations, we
4194
        // simply set the uncommitted preimage slice to nil so that a new one
4195
        // will be initialized if any more witnesses are discovered. We do this
4196
        // because the maximum size that the slice can occupy is 15KB, and we
4197
        // want to ensure we release that memory back to the runtime.
4198
        l.uncommittedPreimages = nil
1,198✔
4199

1,198✔
4200
        // We just received a new updates to our local commitment chain,
1,198✔
4201
        // validate this new commitment, closing the link if invalid.
1,198✔
4202
        auxSigBlob, err := msg.CustomRecords.Serialize()
1,198✔
4203
        if err != nil {
1,198✔
NEW
4204
                l.failf(
×
NEW
4205
                        LinkFailureError{code: ErrInvalidCommitment},
×
NEW
4206
                        "unable to serialize custom records: %v", err,
×
NEW
4207
                )
×
NEW
4208

×
NEW
4209
                return
×
NEW
4210
        }
×
4211
        err = l.channel.ReceiveNewCommitment(&lnwallet.CommitSigs{
1,198✔
4212
                CommitSig:  msg.CommitSig,
1,198✔
4213
                HtlcSigs:   msg.HtlcSigs,
1,198✔
4214
                PartialSig: msg.PartialSig,
1,198✔
4215
                AuxSigBlob: auxSigBlob,
1,198✔
4216
        })
1,198✔
4217
        if err != nil {
1,198✔
NEW
4218
                // If we were unable to reconstruct their proposed commitment,
×
NEW
4219
                // then we'll examine the type of error. If it's an
×
NEW
4220
                // InvalidCommitSigError, then we'll send a direct error.
×
NEW
4221
                var sendData []byte
×
NEW
4222
                switch {
×
NEW
4223
                case lnutils.ErrorAs[*lnwallet.InvalidCommitSigError](err):
×
NEW
4224
                        sendData = []byte(err.Error())
×
NEW
4225
                case lnutils.ErrorAs[*lnwallet.InvalidHtlcSigError](err):
×
NEW
4226
                        sendData = []byte(err.Error())
×
4227
                }
NEW
4228
                l.failf(
×
NEW
4229
                        LinkFailureError{
×
NEW
4230
                                code:          ErrInvalidCommitment,
×
NEW
4231
                                FailureAction: LinkFailureForceClose,
×
NEW
4232
                                SendData:      sendData,
×
NEW
4233
                        },
×
NEW
4234
                        "ChannelPoint(%v): unable to accept new "+
×
NEW
4235
                                "commitment: %v",
×
NEW
4236
                        l.channel.ChannelPoint(), err,
×
NEW
4237
                )
×
NEW
4238

×
NEW
4239
                return
×
4240
        }
4241

4242
        // As we've just accepted a new state, we'll now immediately send the
4243
        // remote peer a revocation for our prior state.
4244
        nextRevocation, currentHtlcs, finalHTLCs, err :=
1,198✔
4245
                l.channel.RevokeCurrentCommitment()
1,198✔
4246
        if err != nil {
1,198✔
NEW
4247
                l.log.Errorf("unable to revoke commitment: %v", err)
×
NEW
4248

×
NEW
4249
                // We need to fail the channel in case revoking our local
×
NEW
4250
                // commitment does not succeed. We might have already advanced
×
NEW
4251
                // our channel state which would lead us to proceed with an
×
NEW
4252
                // unclean state.
×
NEW
4253
                //
×
NEW
4254
                // NOTE: We do not trigger a force close because this could
×
NEW
4255
                // resolve itself in case our db was just busy not accepting new
×
NEW
4256
                // transactions.
×
NEW
4257
                l.failf(
×
NEW
4258
                        LinkFailureError{
×
NEW
4259
                                code:          ErrInternalError,
×
NEW
4260
                                Warning:       true,
×
NEW
4261
                                FailureAction: LinkFailureDisconnect,
×
NEW
4262
                        },
×
NEW
4263
                        "ChannelPoint(%v): unable to accept new "+
×
NEW
4264
                                "commitment: %v",
×
NEW
4265
                        l.channel.ChannelPoint(), err,
×
NEW
4266
                )
×
NEW
4267

×
NEW
4268
                return
×
NEW
4269
        }
×
4270

4271
        // As soon as we are ready to send our next revocation, we can invoke
4272
        // the incoming commit hooks.
4273
        l.Lock()
1,198✔
4274
        l.incomingCommitHooks.invoke()
1,198✔
4275
        l.Unlock()
1,198✔
4276

1,198✔
4277
        err = l.cfg.Peer.SendMessage(false, nextRevocation)
1,198✔
4278
        if err != nil {
1,198✔
NEW
4279
                l.log.Errorf("failed to send RevokeAndAck: %v", err)
×
NEW
4280
        }
×
4281

4282
        // Notify the incoming htlcs of which the resolutions were locked in.
4283
        for id, settled := range finalHTLCs {
1,532✔
4284
                l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
334✔
4285
                        models.CircuitKey{
334✔
4286
                                ChanID: l.ShortChanID(),
334✔
4287
                                HtlcID: id,
334✔
4288
                        },
334✔
4289
                        channeldb.FinalHtlcInfo{
334✔
4290
                                Settled:  settled,
334✔
4291
                                Offchain: true,
334✔
4292
                        },
334✔
4293
                )
334✔
4294
        }
334✔
4295

4296
        // Since we just revoked our commitment, we may have a new set of HTLC's
4297
        // on our commitment, so we'll send them using our function closure
4298
        // NotifyContractUpdate.
4299
        newUpdate := &contractcourt.ContractUpdate{
1,198✔
4300
                HtlcKey: contractcourt.LocalHtlcSet,
1,198✔
4301
                Htlcs:   currentHtlcs,
1,198✔
4302
        }
1,198✔
4303
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,198✔
4304
        if err != nil {
1,198✔
NEW
4305
                l.log.Errorf("unable to notify contract update: %v", err)
×
NEW
4306
                return
×
NEW
4307
        }
×
4308

4309
        select {
1,198✔
NEW
4310
        case <-l.cg.Done():
×
NEW
4311
                return
×
4312
        default:
1,198✔
4313
        }
4314

4315
        // If the remote party initiated the state transition, we'll reply with
4316
        // a signature to provide them with their version of the latest
4317
        // commitment. Otherwise, both commitment chains are fully synced from
4318
        // our PoV, then we don't need to reply with a signature as both sides
4319
        // already have a commitment with the latest accepted.
4320
        if l.channel.OweCommitment() {
1,857✔
4321
                if !l.updateCommitTxOrFail(ctx) {
659✔
NEW
4322
                        return
×
NEW
4323
                }
×
4324
        }
4325

4326
        // If we need to send out an Stfu, this would be the time to do so.
4327
        if l.noDanglingUpdates(lntypes.Local) {
2,285✔
4328
                err = l.quiescer.SendOwedStfu()
1,087✔
4329
                if err != nil {
1,087✔
NEW
4330
                        l.stfuFailf("sendOwedStfu: %v", err.Error())
×
NEW
4331
                }
×
4332
        }
4333

4334
        // Now that we have finished processing the incoming CommitSig and sent
4335
        // out our RevokeAndAck, we invoke the flushHooks if the channel state
4336
        // is clean.
4337
        l.Lock()
1,198✔
4338
        if l.channel.IsChannelClean() {
1,392✔
4339
                l.flushHooks.invoke()
194✔
4340
        }
194✔
4341
        l.Unlock()
1,198✔
4342
}
4343

4344
// processRemoteRevokeAndAck takes a `RevokeAndAck` msg sent from the remote and
4345
// processes it.
4346
func (l *channelLink) processRemoteRevokeAndAck(ctx context.Context,
4347
        msg *lnwire.RevokeAndAck) {
1,187✔
4348

1,187✔
4349
        // We've received a revocation from the remote chain, if valid, this
1,187✔
4350
        // moves the remote chain forward, and expands our revocation window.
1,187✔
4351

1,187✔
4352
        // We now process the message and advance our remote commit chain.
1,187✔
4353
        fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
1,187✔
4354
        if err != nil {
1,187✔
NEW
4355
                // TODO(halseth): force close?
×
NEW
4356
                l.failf(
×
NEW
4357
                        LinkFailureError{
×
NEW
4358
                                code:          ErrInvalidRevocation,
×
NEW
4359
                                FailureAction: LinkFailureDisconnect,
×
NEW
4360
                        },
×
NEW
4361
                        "unable to accept revocation: %v", err,
×
NEW
4362
                )
×
NEW
4363

×
NEW
4364
                return
×
NEW
4365
        }
×
4366

4367
        // The remote party now has a new primary commitment, so we'll update
4368
        // the contract court to be aware of this new set (the prior old remote
4369
        // pending).
4370
        newUpdate := &contractcourt.ContractUpdate{
1,187✔
4371
                HtlcKey: contractcourt.RemoteHtlcSet,
1,187✔
4372
                Htlcs:   remoteHTLCs,
1,187✔
4373
        }
1,187✔
4374
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,187✔
4375
        if err != nil {
1,187✔
NEW
4376
                l.log.Errorf("unable to notify contract update: %v", err)
×
NEW
4377
                return
×
NEW
4378
        }
×
4379

4380
        select {
1,187✔
4381
        case <-l.cg.Done():
1✔
4382
                return
1✔
4383
        default:
1,186✔
4384
        }
4385

4386
        // If we have a tower client for this channel type, we'll create a
4387
        // backup for the current state.
4388
        if l.cfg.TowerClient != nil {
1,189✔
4389
                state := l.channel.State()
3✔
4390
                chanID := l.ChanID()
3✔
4391

3✔
4392
                err = l.cfg.TowerClient.BackupState(
3✔
4393
                        &chanID, state.RemoteCommitment.CommitHeight-1,
3✔
4394
                )
3✔
4395
                if err != nil {
3✔
NEW
4396
                        l.failf(LinkFailureError{
×
NEW
4397
                                code: ErrInternalError,
×
NEW
4398
                        }, "unable to queue breach backup: %v", err)
×
NEW
4399

×
NEW
4400
                        return
×
NEW
4401
                }
×
4402
        }
4403

4404
        // If we can send updates then we can process adds in case we are the
4405
        // exit hop and need to send back resolutions, or in case there are
4406
        // validity issues with the packets. Otherwise we defer the action until
4407
        // resume.
4408
        //
4409
        // We are free to process the settles and fails without this check since
4410
        // processing those can't result in further updates to this channel
4411
        // link.
4412
        if l.quiescer.CanSendUpdates() {
2,371✔
4413
                l.processRemoteAdds(fwdPkg)
1,185✔
4414
        } else {
1,186✔
4415
                l.quiescer.OnResume(func() {
1✔
NEW
4416
                        l.processRemoteAdds(fwdPkg)
×
NEW
4417
                })
×
4418
        }
4419
        l.processRemoteSettleFails(fwdPkg)
1,186✔
4420

1,186✔
4421
        // If the link failed during processing the adds, we must return to
1,186✔
4422
        // ensure we won't attempted to update the state further.
1,186✔
4423
        if l.failed {
1,186✔
NEW
4424
                return
×
NEW
4425
        }
×
4426

4427
        // The revocation window opened up. If there are pending local updates,
4428
        // try to update the commit tx. Pending updates could already have been
4429
        // present because of a previously failed update to the commit tx or
4430
        // freshly added in by processRemoteAdds. Also in case there are no
4431
        // local updates, but there are still remote updates that are not in the
4432
        // remote commit tx yet, send out an update.
4433
        if l.channel.OweCommitment() {
1,504✔
4434
                if !l.updateCommitTxOrFail(ctx) {
325✔
4435
                        return
7✔
4436
                }
7✔
4437
        }
4438

4439
        // Now that we have finished processing the RevokeAndAck, we can invoke
4440
        // the flushHooks if the channel state is clean.
4441
        l.Lock()
1,179✔
4442
        if l.channel.IsChannelClean() {
1,342✔
4443
                l.flushHooks.invoke()
163✔
4444
        }
163✔
4445
        l.Unlock()
1,179✔
4446
}
4447

4448
// processRemoteUpdateFee takes an `UpdateFee` msg sent from the remote and
4449
// processes it.
4450
func (l *channelLink) processRemoteUpdateFee(msg *lnwire.UpdateFee) {
3✔
4451
        // Check and see if their proposed fee-rate would make us exceed the fee
3✔
4452
        // threshold.
3✔
4453
        fee := chainfee.SatPerKWeight(msg.FeePerKw)
3✔
4454

3✔
4455
        isDust, err := l.exceedsFeeExposureLimit(fee)
3✔
4456
        if err != nil {
3✔
NEW
4457
                // This shouldn't typically happen. If it does, it indicates
×
NEW
4458
                // something is wrong with our channel state.
×
NEW
4459
                l.log.Errorf("Unable to determine if fee threshold " +
×
NEW
4460
                        "exceeded")
×
NEW
4461
                l.failf(LinkFailureError{code: ErrInternalError},
×
NEW
4462
                        "error calculating fee exposure: %v", err)
×
NEW
4463

×
NEW
4464
                return
×
NEW
4465
        }
×
4466

4467
        if isDust {
3✔
NEW
4468
                // The proposed fee-rate makes us exceed the fee threshold.
×
NEW
4469
                l.failf(LinkFailureError{code: ErrInternalError},
×
NEW
4470
                        "fee threshold exceeded: %v", err)
×
NEW
4471
                return
×
NEW
4472
        }
×
4473

4474
        // We received fee update from peer. If we are the initiator we will
4475
        // fail the channel, if not we will apply the update.
4476
        if err := l.channel.ReceiveUpdateFee(fee); err != nil {
3✔
NEW
4477
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
NEW
4478
                        "error receiving fee update: %v", err)
×
NEW
4479
                return
×
NEW
4480
        }
×
4481

4482
        // Update the mailbox's feerate as well.
4483
        l.mailBox.SetFeeRate(fee)
3✔
4484
}
4485

4486
// processRemoteError takes an `Error` msg sent from the remote and fails the
4487
// channel link.
4488
func (l *channelLink) processRemoteError(msg *lnwire.Error) {
2✔
4489
        // Error received from remote, MUST fail channel, but should only print
2✔
4490
        // the contents of the error message if all characters are printable
2✔
4491
        // ASCII.
2✔
4492
        l.failf(
2✔
4493
                // TODO(halseth): we currently don't fail the channel
2✔
4494
                // permanently, as there are some sync issues with other
2✔
4495
                // implementations that will lead to them sending an
2✔
4496
                // error message, but we can recover from on next
2✔
4497
                // connection. See
2✔
4498
                // https://github.com/ElementsProject/lightning/issues/4212
2✔
4499
                LinkFailureError{
2✔
4500
                        code:             ErrRemoteError,
2✔
4501
                        PermanentFailure: false,
2✔
4502
                },
2✔
4503
                "ChannelPoint(%v): received error from peer: %v",
2✔
4504
                l.channel.ChannelPoint(), msg.Error(),
2✔
4505
        )
2✔
4506
}
2✔
4507

4508
// processLocalUpdateFulfillHTLC takes an `UpdateFulfillHTLC` from the local and
4509
// processes it.
4510
func (l *channelLink) processLocalUpdateFulfillHTLC(ctx context.Context,
4511
        pkt *htlcPacket, htlc *lnwire.UpdateFulfillHTLC) {
26✔
4512

26✔
4513
        // If hodl.SettleOutgoing mode is active, we exit early to simulate
26✔
4514
        // arbitrary delays between the switch adding the SETTLE to the mailbox,
26✔
4515
        // and the HTLC being added to the commitment state.
26✔
4516
        if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
26✔
NEW
4517
                l.log.Warnf(hodl.SettleOutgoing.Warning())
×
NEW
4518
                l.mailBox.AckPacket(pkt.inKey())
×
NEW
4519

×
NEW
4520
                return
×
NEW
4521
        }
×
4522

4523
        // An HTLC we forward to the switch has just settled somewhere upstream.
4524
        // Therefore we settle the HTLC within the our local state machine.
4525
        inKey := pkt.inKey()
26✔
4526
        err := l.channel.SettleHTLC(
26✔
4527
                htlc.PaymentPreimage, pkt.incomingHTLCID, pkt.sourceRef,
26✔
4528
                pkt.destRef, &inKey,
26✔
4529
        )
26✔
4530
        if err != nil {
26✔
NEW
4531
                l.log.Errorf("unable to settle incoming HTLC for "+
×
NEW
4532
                        "circuit-key=%v: %v", inKey, err)
×
NEW
4533

×
NEW
4534
                // If the HTLC index for Settle response was not known to our
×
NEW
4535
                // commitment state, it has already been cleaned up by a prior
×
NEW
4536
                // response. We'll thus try to clean up any lingering state to
×
NEW
4537
                // ensure we don't continue reforwarding.
×
NEW
4538
                if lnutils.ErrorAs[lnwallet.ErrUnknownHtlcIndex](err) {
×
NEW
4539
                        l.cleanupSpuriousResponse(pkt)
×
NEW
4540
                }
×
4541

4542
                // Remove the packet from the link's mailbox to ensure it
4543
                // doesn't get replayed after a reconnection.
NEW
4544
                l.mailBox.AckPacket(inKey)
×
NEW
4545

×
NEW
4546
                return
×
4547
        }
4548

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

26✔
4552
        l.closedCircuits = append(l.closedCircuits, pkt.inKey())
26✔
4553

26✔
4554
        // With the HTLC settled, we'll need to populate the wire message to
26✔
4555
        // target the specific channel and HTLC to be canceled.
26✔
4556
        htlc.ChanID = l.ChanID()
26✔
4557
        htlc.ID = pkt.incomingHTLCID
26✔
4558

26✔
4559
        // Then we send the HTLC settle message to the connected peer so we can
26✔
4560
        // continue the propagation of the settle message.
26✔
4561
        err = l.cfg.Peer.SendMessage(false, htlc)
26✔
4562
        if err != nil {
26✔
NEW
4563
                l.log.Errorf("failed to send UpdateFulfillHTLC: %v", err)
×
NEW
4564
        }
×
4565

4566
        // Send a settle event notification to htlcNotifier.
4567
        l.cfg.HtlcNotifier.NotifySettleEvent(
26✔
4568
                newHtlcKey(pkt), htlc.PaymentPreimage, getEventType(pkt),
26✔
4569
        )
26✔
4570

26✔
4571
        // Immediately update the commitment tx to minimize latency.
26✔
4572
        l.updateCommitTxOrFail(ctx)
26✔
4573
}
4574

4575
// processLocalUpdateFailHTLC takes an `UpdateFailHTLC` from the local and
4576
// processes it.
4577
func (l *channelLink) processLocalUpdateFailHTLC(ctx context.Context,
4578
        pkt *htlcPacket, htlc *lnwire.UpdateFailHTLC) {
21✔
4579

21✔
4580
        // If hodl.FailOutgoing mode is active, we exit early to simulate
21✔
4581
        // arbitrary delays between the switch adding a FAIL to the mailbox, and
21✔
4582
        // the HTLC being added to the commitment state.
21✔
4583
        if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
21✔
NEW
4584
                l.log.Warnf(hodl.FailOutgoing.Warning())
×
NEW
4585
                l.mailBox.AckPacket(pkt.inKey())
×
NEW
4586

×
NEW
4587
                return
×
NEW
4588
        }
×
4589

4590
        // An HTLC cancellation has been triggered somewhere upstream, we'll
4591
        // remove then HTLC from our local state machine.
4592
        inKey := pkt.inKey()
21✔
4593
        err := l.channel.FailHTLC(
21✔
4594
                pkt.incomingHTLCID, htlc.Reason, pkt.sourceRef, pkt.destRef,
21✔
4595
                &inKey,
21✔
4596
        )
21✔
4597
        if err != nil {
26✔
4598
                l.log.Errorf("unable to cancel incoming HTLC for "+
5✔
4599
                        "circuit-key=%v: %v", inKey, err)
5✔
4600

5✔
4601
                // If the HTLC index for Fail response was not known to our
5✔
4602
                // commitment state, it has already been cleaned up by a prior
5✔
4603
                // response. We'll thus try to clean up any lingering state to
5✔
4604
                // ensure we don't continue reforwarding.
5✔
4605
                if lnutils.ErrorAs[lnwallet.ErrUnknownHtlcIndex](err) {
7✔
4606
                        l.cleanupSpuriousResponse(pkt)
2✔
4607
                }
2✔
4608

4609
                // Remove the packet from the link's mailbox to ensure it
4610
                // doesn't get replayed after a reconnection.
4611
                l.mailBox.AckPacket(inKey)
5✔
4612

5✔
4613
                return
5✔
4614
        }
4615

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

19✔
4619
        l.closedCircuits = append(l.closedCircuits, pkt.inKey())
19✔
4620

19✔
4621
        // With the HTLC removed, we'll need to populate the wire message to
19✔
4622
        // target the specific channel and HTLC to be canceled. The "Reason"
19✔
4623
        // field will have already been set within the switch.
19✔
4624
        htlc.ChanID = l.ChanID()
19✔
4625
        htlc.ID = pkt.incomingHTLCID
19✔
4626

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

×
NEW
4635
                return
×
NEW
4636
        }
×
4637

4638
        // If the packet does not have a link failure set, it failed further
4639
        // down the route so we notify a forwarding failure. Otherwise, we
4640
        // notify a link failure because it failed at our node.
4641
        if pkt.linkFailure != nil {
32✔
4642
                l.cfg.HtlcNotifier.NotifyLinkFailEvent(
13✔
4643
                        newHtlcKey(pkt), newHtlcInfo(pkt), getEventType(pkt),
13✔
4644
                        pkt.linkFailure, false,
13✔
4645
                )
13✔
4646
        } else {
22✔
4647
                l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
9✔
4648
                        newHtlcKey(pkt), getEventType(pkt),
9✔
4649
                )
9✔
4650
        }
9✔
4651

4652
        // Immediately update the commitment tx to minimize latency.
4653
        l.updateCommitTxOrFail(ctx)
19✔
4654
}
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