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

lightningnetwork / lnd / 12313073348

13 Dec 2024 09:30AM UTC coverage: 58.666% (+1.2%) from 57.486%
12313073348

Pull #9344

github

ellemouton
htlcswitch+go.mod: use updated fn.ContextGuard

This commit updates the fn dep to the version containing the updates to
the ContextGuard implementation. Only the htlcswitch/link uses the guard
at the moment so this is updated to make use of the new implementation.
Pull Request #9344: htlcswitch+go.mod: use updated fn.ContextGuard

101 of 117 new or added lines in 4 files covered. (86.32%)

29 existing lines in 9 files now uncovered.

134589 of 229415 relevant lines covered (58.67%)

19278.57 hits per line

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

78.56
/htlcswitch/link.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

370
        sync.RWMutex
371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6✔
455
        return hookID
6✔
456
}
457

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

217✔
603
        return nil
217✔
604
}
605

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

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

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

206✔
622
        if l.cfg.ChainEvents.Cancel != nil {
210✔
623
                l.cfg.ChainEvents.Cancel()
4✔
624
        }
4✔
625

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

785
        return out
5✔
786
}
787

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

884
        return cb(update)
26✔
885
}
886

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

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

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

909
        var msgsToReSend []lnwire.Message
174✔
910

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1029
        return nil
174✔
1030
}
1031

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

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

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

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

1057
        return nil
216✔
1058
}
1059

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

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

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

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

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

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

1105
        return nil
10✔
1106
}
1107

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1259
        l.log.Infof("HTLC manager started, bandwidth=%v", l.Bandwidth())
217✔
1260

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

217✔
1268
        // TODO(roasbeef): need to call wipe chan whenever D/C?
217✔
1269

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

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

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

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

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

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

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

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

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

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

1353
        for {
4,417✔
1354
                // We must always check if we failed at some point processing
4,201✔
1355
                // the last update before processing the next.
4,201✔
1356
                if l.failed {
4,218✔
1357
                        l.log.Errorf("link failed, exiting htlcManager")
17✔
1358
                        return
17✔
1359
                }
17✔
1360

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

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

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

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

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

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

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

1429
                        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
4✔
1430

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

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

1✔
1446
                                continue
1✔
1447
                        }
1448

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

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

4✔
1467
                        // TODO(roasbeef): remove all together
4✔
1468
                        go func() {
8✔
1469
                                chanPoint := l.channel.ChannelPoint()
4✔
1470
                                l.cfg.Peer.WipeChannel(&chanPoint)
4✔
1471
                        }()
4✔
1472

1473
                        return
4✔
1474

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

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

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

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

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

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

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

1534
                case qReq := <-l.quiescenceReqs:
5✔
1535
                        l.quiescer.InitStfu(qReq)
5✔
1536

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

1548
                case <-l.cg.Done():
193✔
1549
                        return
193✔
1550
                }
1551
        }
1552
}
1553

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

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

1573
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
59✔
1574
                        return err
×
1575
                }
×
1576

1577
                // Clean up hodl map.
1578
                delete(l.hodlMap, circuitKey)
59✔
1579

59✔
1580
                select {
59✔
1581
                case item := <-l.hodlQueue.ChanOut():
4✔
1582
                        htlcResolution = item.(invoices.HtlcResolution)
4✔
1583
                default:
59✔
1584
                        break loop
59✔
1585
                }
1586
        }
1587

1588
        // Update the commitment tx.
1589
        if err := l.updateCommitTx(ctx); err != nil {
60✔
1590
                return err
1✔
1591
        }
1✔
1592

1593
        return nil
58✔
1594
}
1595

1596
// processHtlcResolution applies a received htlc resolution to the provided
1597
// htlc. When this function returns without an error, the commit tx should be
1598
// updated.
1599
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1600
        htlc hodlHtlc) error {
205✔
1601

205✔
1602
        circuitKey := resolution.CircuitKey()
205✔
1603

205✔
1604
        // Determine required action for the resolution based on the type of
205✔
1605
        // resolution we have received.
205✔
1606
        switch res := resolution.(type) {
205✔
1607
        // Settle htlcs that returned a settle resolution using the preimage
1608
        // in the resolution.
1609
        case *invoices.HtlcSettleResolution:
201✔
1610
                l.log.Debugf("received settle resolution for %v "+
201✔
1611
                        "with outcome: %v", circuitKey, res.Outcome)
201✔
1612

201✔
1613
                return l.settleHTLC(
201✔
1614
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
201✔
1615
                )
201✔
1616

1617
        // For htlc failures, we get the relevant failure message based
1618
        // on the failure resolution and then fail the htlc.
1619
        case *invoices.HtlcFailResolution:
8✔
1620
                l.log.Debugf("received cancel resolution for "+
8✔
1621
                        "%v with outcome: %v", circuitKey, res.Outcome)
8✔
1622

8✔
1623
                // Get the lnwire failure message based on the resolution
8✔
1624
                // result.
8✔
1625
                failure := getResolutionFailure(res, htlc.add.Amount)
8✔
1626

8✔
1627
                l.sendHTLCError(
8✔
1628
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
8✔
1629
                        true,
8✔
1630
                )
8✔
1631
                return nil
8✔
1632

1633
        // Fail if we do not get a settle of fail resolution, since we
1634
        // are only expecting to handle settles and fails.
1635
        default:
×
1636
                return fmt.Errorf("unknown htlc resolution type: %T",
×
1637
                        resolution)
×
1638
        }
1639
}
1640

1641
// getResolutionFailure returns the wire message that a htlc resolution should
1642
// be failed with.
1643
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1644
        amount lnwire.MilliSatoshi) *LinkError {
8✔
1645

8✔
1646
        // If the resolution has been resolved as part of a MPP timeout,
8✔
1647
        // we need to fail the htlc with lnwire.FailMppTimeout.
8✔
1648
        if resolution.Outcome == invoices.ResultMppTimeout {
8✔
1649
                return NewDetailedLinkError(
×
1650
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
1651
                )
×
1652
        }
×
1653

1654
        // If the htlc is not a MPP timeout, we fail it with
1655
        // FailIncorrectDetails. This error is sent for invoice payment
1656
        // failures such as underpayment/ expiry too soon and hodl invoices
1657
        // (which return FailIncorrectDetails to avoid leaking information).
1658
        incorrectDetails := lnwire.NewFailIncorrectDetails(
8✔
1659
                amount, uint32(resolution.AcceptHeight),
8✔
1660
        )
8✔
1661

8✔
1662
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
8✔
1663
}
1664

1665
// randomFeeUpdateTimeout returns a random timeout between the bounds defined
1666
// within the link's configuration that will be used to determine when the link
1667
// should propose an update to its commitment fee rate.
1668
func (l *channelLink) randomFeeUpdateTimeout() time.Duration {
221✔
1669
        lower := int64(l.cfg.MinUpdateTimeout)
221✔
1670
        upper := int64(l.cfg.MaxUpdateTimeout)
221✔
1671
        return time.Duration(prand.Int63n(upper-lower) + lower)
221✔
1672
}
221✔
1673

1674
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1675
// downstream HTLC Switch.
1676
func (l *channelLink) handleDownstreamUpdateAdd(ctx context.Context,
1677
        pkt *htlcPacket) error {
484✔
1678

484✔
1679
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
484✔
1680
        if !ok {
484✔
1681
                return errors.New("not an UpdateAddHTLC packet")
×
1682
        }
×
1683

1684
        // If we are flushing the link in the outgoing direction or we have
1685
        // already sent Stfu, then we can't add new htlcs to the link and we
1686
        // need to bounce it.
1687
        if l.IsFlushing(Outgoing) || !l.quiescer.CanSendUpdates() {
484✔
1688
                l.mailBox.FailAdd(pkt)
×
1689

×
1690
                return NewDetailedLinkError(
×
1691
                        &lnwire.FailTemporaryChannelFailure{},
×
1692
                        OutgoingFailureLinkNotEligible,
×
1693
                )
×
1694
        }
×
1695

1696
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1697
        // arbitrary delays between the switch adding an ADD to the
1698
        // mailbox, and the HTLC being added to the commitment state.
1699
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
484✔
1700
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
1701
                l.mailBox.AckPacket(pkt.inKey())
×
1702
                return nil
×
1703
        }
×
1704

1705
        // Check if we can add the HTLC here without exceededing the max fee
1706
        // exposure threshold.
1707
        if l.isOverexposedWithHtlc(htlc, false) {
488✔
1708
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1709
                        "exposure exceeded")
4✔
1710

4✔
1711
                l.mailBox.FailAdd(pkt)
4✔
1712

4✔
1713
                return NewDetailedLinkError(
4✔
1714
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1715
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1716
                )
4✔
1717
        }
4✔
1718

1719
        // A new payment has been initiated via the downstream channel,
1720
        // so we add the new HTLC to our local log, then update the
1721
        // commitment chains.
1722
        htlc.ChanID = l.ChanID()
480✔
1723
        openCircuitRef := pkt.inKey()
480✔
1724

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

5✔
1737
                // Remove this packet from the link's mailbox, this
5✔
1738
                // prevents it from being reprocessed if the link
5✔
1739
                // restarts and resets it mailbox. If this response
5✔
1740
                // doesn't make it back to the originating link, it will
5✔
1741
                // be rejected upon attempting to reforward the Add to
5✔
1742
                // the switch, since the circuit was never fully opened,
5✔
1743
                // and the forwarding package shows it as
5✔
1744
                // unacknowledged.
5✔
1745
                l.mailBox.FailAdd(pkt)
5✔
1746

5✔
1747
                return NewDetailedLinkError(
5✔
1748
                        lnwire.NewTemporaryChannelFailure(nil),
5✔
1749
                        OutgoingFailureDownstreamHtlcAdd,
5✔
1750
                )
5✔
1751
        }
5✔
1752

1753
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
479✔
1754
                "local_log_index=%v, pend_updates=%v",
479✔
1755
                htlc.PaymentHash[:], index,
479✔
1756
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
479✔
1757

479✔
1758
        pkt.outgoingChanID = l.ShortChanID()
479✔
1759
        pkt.outgoingHTLCID = index
479✔
1760
        htlc.ID = index
479✔
1761

479✔
1762
        l.log.Debugf("queueing keystone of ADD open circuit: %s->%s",
479✔
1763
                pkt.inKey(), pkt.outKey())
479✔
1764

479✔
1765
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
479✔
1766
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
479✔
1767

479✔
1768
        _ = l.cfg.Peer.SendMessage(false, htlc)
479✔
1769

479✔
1770
        // Send a forward event notification to htlcNotifier.
479✔
1771
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
479✔
1772
                newHtlcKey(pkt),
479✔
1773
                HtlcInfo{
479✔
1774
                        IncomingTimeLock: pkt.incomingTimeout,
479✔
1775
                        IncomingAmt:      pkt.incomingAmount,
479✔
1776
                        OutgoingTimeLock: htlc.Expiry,
479✔
1777
                        OutgoingAmt:      htlc.Amount,
479✔
1778
                },
479✔
1779
                getEventType(pkt),
479✔
1780
        )
479✔
1781

479✔
1782
        l.tryBatchUpdateCommitTx(ctx)
479✔
1783

479✔
1784
        return nil
479✔
1785
}
1786

1787
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1788
// Switch. Possible messages sent by the switch include requests to forward new
1789
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1790
// cleared HTLCs with the upstream peer.
1791
//
1792
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1793
func (l *channelLink) handleDownstreamPkt(ctx context.Context,
1794
        pkt *htlcPacket) {
525✔
1795

525✔
1796
        if pkt.htlc.MsgType().IsChannelUpdate() &&
525✔
1797
                !l.quiescer.CanSendUpdates() {
525✔
1798

×
1799
                l.log.Warnf("unable to process channel update. "+
×
1800
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1801

×
1802
                return
×
1803
        }
×
1804

1805
        switch htlc := pkt.htlc.(type) {
525✔
1806
        case *lnwire.UpdateAddHTLC:
484✔
1807
                // Handle add message. The returned error can be ignored,
484✔
1808
                // because it is also sent through the mailbox.
484✔
1809
                _ = l.handleDownstreamUpdateAdd(ctx, pkt)
484✔
1810

1811
        case *lnwire.UpdateFulfillHTLC:
27✔
1812
                // If hodl.SettleOutgoing mode is active, we exit early to
27✔
1813
                // simulate arbitrary delays between the switch adding the
27✔
1814
                // SETTLE to the mailbox, and the HTLC being added to the
27✔
1815
                // commitment state.
27✔
1816
                if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
27✔
1817
                        l.log.Warnf(hodl.SettleOutgoing.Warning())
×
1818
                        l.mailBox.AckPacket(pkt.inKey())
×
1819
                        return
×
1820
                }
×
1821

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

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

1846
                        // Remove the packet from the link's mailbox to ensure
1847
                        // it doesn't get replayed after a reconnection.
1848
                        l.mailBox.AckPacket(inKey)
×
1849

×
1850
                        return
×
1851
                }
1852

1853
                l.log.Debugf("queueing removal of SETTLE closed circuit: "+
27✔
1854
                        "%s->%s", pkt.inKey(), pkt.outKey())
27✔
1855

27✔
1856
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
27✔
1857

27✔
1858
                // With the HTLC settled, we'll need to populate the wire
27✔
1859
                // message to target the specific channel and HTLC to be
27✔
1860
                // canceled.
27✔
1861
                htlc.ChanID = l.ChanID()
27✔
1862
                htlc.ID = pkt.incomingHTLCID
27✔
1863

27✔
1864
                // Then we send the HTLC settle message to the connected peer
27✔
1865
                // so we can continue the propagation of the settle message.
27✔
1866
                l.cfg.Peer.SendMessage(false, htlc)
27✔
1867

27✔
1868
                // Send a settle event notification to htlcNotifier.
27✔
1869
                l.cfg.HtlcNotifier.NotifySettleEvent(
27✔
1870
                        newHtlcKey(pkt),
27✔
1871
                        htlc.PaymentPreimage,
27✔
1872
                        getEventType(pkt),
27✔
1873
                )
27✔
1874

27✔
1875
                // Immediately update the commitment tx to minimize latency.
27✔
1876
                l.updateCommitTxOrFail(ctx)
27✔
1877

1878
        case *lnwire.UpdateFailHTLC:
22✔
1879
                // If hodl.FailOutgoing mode is active, we exit early to
22✔
1880
                // simulate arbitrary delays between the switch adding a FAIL to
22✔
1881
                // the mailbox, and the HTLC being added to the commitment
22✔
1882
                // state.
22✔
1883
                if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
22✔
1884
                        l.log.Warnf(hodl.FailOutgoing.Warning())
×
1885
                        l.mailBox.AckPacket(pkt.inKey())
×
1886
                        return
×
1887
                }
×
1888

1889
                // An HTLC cancellation has been triggered somewhere upstream,
1890
                // we'll remove then HTLC from our local state machine.
1891
                inKey := pkt.inKey()
22✔
1892
                err := l.channel.FailHTLC(
22✔
1893
                        pkt.incomingHTLCID,
22✔
1894
                        htlc.Reason,
22✔
1895
                        pkt.sourceRef,
22✔
1896
                        pkt.destRef,
22✔
1897
                        &inKey,
22✔
1898
                )
22✔
1899
                if err != nil {
28✔
1900
                        l.log.Errorf("unable to cancel incoming HTLC for "+
6✔
1901
                                "circuit-key=%v: %v", inKey, err)
6✔
1902

6✔
1903
                        // If the HTLC index for Fail response was not known to
6✔
1904
                        // our commitment state, it has already been cleaned up
6✔
1905
                        // by a prior response. We'll thus try to clean up any
6✔
1906
                        // lingering state to ensure we don't continue
6✔
1907
                        // reforwarding.
6✔
1908
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
8✔
1909
                                l.cleanupSpuriousResponse(pkt)
2✔
1910
                        }
2✔
1911

1912
                        // Remove the packet from the link's mailbox to ensure
1913
                        // it doesn't get replayed after a reconnection.
1914
                        l.mailBox.AckPacket(inKey)
6✔
1915

6✔
1916
                        return
6✔
1917
                }
1918

1919
                l.log.Debugf("queueing removal of FAIL closed circuit: %s->%s",
20✔
1920
                        pkt.inKey(), pkt.outKey())
20✔
1921

20✔
1922
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
20✔
1923

20✔
1924
                // With the HTLC removed, we'll need to populate the wire
20✔
1925
                // message to target the specific channel and HTLC to be
20✔
1926
                // canceled. The "Reason" field will have already been set
20✔
1927
                // within the switch.
20✔
1928
                htlc.ChanID = l.ChanID()
20✔
1929
                htlc.ID = pkt.incomingHTLCID
20✔
1930

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

×
1944
                        return
×
1945
                }
×
1946

1947
                // If the packet does not have a link failure set, it failed
1948
                // further down the route so we notify a forwarding failure.
1949
                // Otherwise, we notify a link failure because it failed at our
1950
                // node.
1951
                if pkt.linkFailure != nil {
34✔
1952
                        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
14✔
1953
                                newHtlcKey(pkt),
14✔
1954
                                newHtlcInfo(pkt),
14✔
1955
                                getEventType(pkt),
14✔
1956
                                pkt.linkFailure,
14✔
1957
                                false,
14✔
1958
                        )
14✔
1959
                } else {
24✔
1960
                        l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
10✔
1961
                                newHtlcKey(pkt), getEventType(pkt),
10✔
1962
                        )
10✔
1963
                }
10✔
1964

1965
                // Immediately update the commitment tx to minimize latency.
1966
                l.updateCommitTxOrFail(ctx)
20✔
1967
        }
1968
}
1969

1970
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1971
// full.
1972
func (l *channelLink) tryBatchUpdateCommitTx(ctx context.Context) {
479✔
1973
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
479✔
1974
        if pending < uint64(l.cfg.BatchSize) {
944✔
1975
                return
465✔
1976
        }
465✔
1977

1978
        l.updateCommitTxOrFail(ctx)
18✔
1979
}
1980

1981
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1982
// associated with this packet. If successful in doing so, it will also purge
1983
// the open circuit from the circuit map and remove the packet from the link's
1984
// mailbox.
1985
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
2✔
1986
        inKey := pkt.inKey()
2✔
1987

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

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

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

×
2008
                // If this operation failed, it is unsafe to attempt removal of
×
2009
                // the destination reference or circuit, so we exit early. The
×
2010
                // cleanup may proceed with a different packet in the future
×
2011
                // that succeeds on this step.
×
2012
                return
×
2013
        }
×
2014

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

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

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

2045
// handleUpstreamMsg processes wire messages related to commitment state
2046
// updates from the upstream peer. The upstream peer is the peer whom we have a
2047
// direct channel with, updating our respective commitment chains.
2048
func (l *channelLink) handleUpstreamMsg(ctx context.Context, msg lnwire.Message) {
3,213✔
2049
        // First check if the message is an update and we are capable of
3,213✔
2050
        // receiving updates right now.
3,213✔
2051
        if msg.MsgType().IsChannelUpdate() && !l.quiescer.CanRecvUpdates() {
3,213✔
2052
                l.stfuFailf("update received after stfu: %T", msg)
×
2053
                return
×
2054
        }
×
2055

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

×
2088
                        return
×
2089
                }
×
2090

2091
                // Disallow htlcs with blinding points set if we haven't
2092
                // enabled the feature. This saves us from having to process
2093
                // the onion at all, but will only catch blinded payments
2094
                // where we are a relaying node (as the blinding point will
2095
                // be in the payload when we're the introduction node).
2096
                if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
454✔
2097
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2098
                                "blinding point included when route blinding "+
×
2099
                                        "is disabled")
×
2100

×
2101
                        return
×
2102
                }
×
2103

2104
                // We have to check the limit here rather than later in the
2105
                // switch because the counterparty can keep sending HTLC's
2106
                // without sending a revoke. This would mean that the switch
2107
                // check would only occur later.
2108
                if l.isOverexposedWithHtlc(msg, true) {
454✔
2109
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2110
                                "peer sent us an HTLC that exceeded our max "+
×
2111
                                        "fee exposure")
×
2112

×
2113
                        return
×
2114
                }
×
2115

2116
                // We just received an add request from an upstream peer, so we
2117
                // add it to our state machine, then add the HTLC to our
2118
                // "settle" list in the event that we know the preimage.
2119
                index, err := l.channel.ReceiveHTLC(msg)
454✔
2120
                if err != nil {
454✔
2121
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2122
                                "unable to handle upstream add HTLC: %v", err)
×
2123
                        return
×
2124
                }
×
2125

2126
                l.log.Tracef("receive upstream htlc with payment hash(%x), "+
454✔
2127
                        "assigning index: %v", msg.PaymentHash[:], index)
454✔
2128

2129
        case *lnwire.UpdateFulfillHTLC:
231✔
2130
                pre := msg.PaymentPreimage
231✔
2131
                idx := msg.ID
231✔
2132

231✔
2133
                // Before we pipeline the settle, we'll check the set of active
231✔
2134
                // htlc's to see if the related UpdateAddHTLC has been fully
231✔
2135
                // locked-in.
231✔
2136
                var lockedin bool
231✔
2137
                htlcs := l.channel.ActiveHtlcs()
231✔
2138
                for _, add := range htlcs {
1,272✔
2139
                        // The HTLC will be outgoing and match idx.
1,041✔
2140
                        if !add.Incoming && add.HtlcIndex == idx {
1,270✔
2141
                                lockedin = true
229✔
2142
                                break
229✔
2143
                        }
2144
                }
2145

2146
                if !lockedin {
233✔
2147
                        l.failf(
2✔
2148
                                LinkFailureError{code: ErrInvalidUpdate},
2✔
2149
                                "unable to handle upstream settle",
2✔
2150
                        )
2✔
2151
                        return
2✔
2152
                }
2✔
2153

2154
                if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
233✔
2155
                        l.failf(
4✔
2156
                                LinkFailureError{
4✔
2157
                                        code:          ErrInvalidUpdate,
4✔
2158
                                        FailureAction: LinkFailureForceClose,
4✔
2159
                                },
4✔
2160
                                "unable to handle upstream settle HTLC: %v", err,
4✔
2161
                        )
4✔
2162
                        return
4✔
2163
                }
4✔
2164

2165
                settlePacket := &htlcPacket{
229✔
2166
                        outgoingChanID: l.ShortChanID(),
229✔
2167
                        outgoingHTLCID: idx,
229✔
2168
                        htlc: &lnwire.UpdateFulfillHTLC{
229✔
2169
                                PaymentPreimage: pre,
229✔
2170
                        },
229✔
2171
                }
229✔
2172

229✔
2173
                // Add the newly discovered preimage to our growing list of
229✔
2174
                // uncommitted preimage. These will be written to the witness
229✔
2175
                // cache just before accepting the next commitment signature
229✔
2176
                // from the remote peer.
229✔
2177
                l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
229✔
2178

229✔
2179
                // Pipeline this settle, send it to the switch.
229✔
2180
                go l.forwardBatch(false, settlePacket)
229✔
2181

2182
        case *lnwire.UpdateFailMalformedHTLC:
7✔
2183
                // Convert the failure type encoded within the HTLC fail
7✔
2184
                // message to the proper generic lnwire error code.
7✔
2185
                var failure lnwire.FailureMessage
7✔
2186
                switch msg.FailureCode {
7✔
2187
                case lnwire.CodeInvalidOnionVersion:
5✔
2188
                        failure = &lnwire.FailInvalidOnionVersion{
5✔
2189
                                OnionSHA256: msg.ShaOnionBlob,
5✔
2190
                        }
5✔
2191
                case lnwire.CodeInvalidOnionHmac:
×
2192
                        failure = &lnwire.FailInvalidOnionHmac{
×
2193
                                OnionSHA256: msg.ShaOnionBlob,
×
2194
                        }
×
2195

2196
                case lnwire.CodeInvalidOnionKey:
×
2197
                        failure = &lnwire.FailInvalidOnionKey{
×
2198
                                OnionSHA256: msg.ShaOnionBlob,
×
2199
                        }
×
2200

2201
                // Handle malformed errors that are part of a blinded route.
2202
                // This case is slightly different, because we expect every
2203
                // relaying node in the blinded portion of the route to send
2204
                // malformed errors. If we're also a relaying node, we're
2205
                // likely going to switch this error out anyway for our own
2206
                // malformed error, but we handle the case here for
2207
                // completeness.
2208
                case lnwire.CodeInvalidBlinding:
4✔
2209
                        failure = &lnwire.FailInvalidBlinding{
4✔
2210
                                OnionSHA256: msg.ShaOnionBlob,
4✔
2211
                        }
4✔
2212

2213
                default:
2✔
2214
                        l.log.Warnf("unexpected failure code received in "+
2✔
2215
                                "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
2216

2✔
2217
                        // We don't just pass back the error we received from
2✔
2218
                        // our successor. Otherwise we might report a failure
2✔
2219
                        // that penalizes us more than needed. If the onion that
2✔
2220
                        // we forwarded was correct, the node should have been
2✔
2221
                        // able to send back its own failure. The node did not
2✔
2222
                        // send back its own failure, so we assume there was a
2✔
2223
                        // problem with the onion and report that back. We reuse
2✔
2224
                        // the invalid onion key failure because there is no
2✔
2225
                        // specific error for this case.
2✔
2226
                        failure = &lnwire.FailInvalidOnionKey{
2✔
2227
                                OnionSHA256: msg.ShaOnionBlob,
2✔
2228
                        }
2✔
2229
                }
2230

2231
                // With the error parsed, we'll convert the into it's opaque
2232
                // form.
2233
                var b bytes.Buffer
7✔
2234
                if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
7✔
2235
                        l.log.Errorf("unable to encode malformed error: %v", err)
×
2236
                        return
×
2237
                }
×
2238

2239
                // If remote side have been unable to parse the onion blob we
2240
                // have sent to it, than we should transform the malformed HTLC
2241
                // message to the usual HTLC fail message.
2242
                err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
7✔
2243
                if err != nil {
7✔
2244
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2245
                                "unable to handle upstream fail HTLC: %v", err)
×
2246
                        return
×
2247
                }
×
2248

2249
        case *lnwire.UpdateFailHTLC:
124✔
2250
                // Verify that the failure reason is at least 256 bytes plus
124✔
2251
                // overhead.
124✔
2252
                const minimumFailReasonLength = lnwire.FailureMessageLength +
124✔
2253
                        2 + 2 + 32
124✔
2254

124✔
2255
                if len(msg.Reason) < minimumFailReasonLength {
125✔
2256
                        // We've received a reason with a non-compliant length.
1✔
2257
                        // Older nodes happily relay back these failures that
1✔
2258
                        // may originate from a node further downstream.
1✔
2259
                        // Therefore we can't just fail the channel.
1✔
2260
                        //
1✔
2261
                        // We want to be compliant ourselves, so we also can't
1✔
2262
                        // pass back the reason unmodified. And we must make
1✔
2263
                        // sure that we don't hit the magic length check of 260
1✔
2264
                        // bytes in processRemoteSettleFails either.
1✔
2265
                        //
1✔
2266
                        // Because the reason is unreadable for the payer
1✔
2267
                        // anyway, we just replace it by a compliant-length
1✔
2268
                        // series of random bytes.
1✔
2269
                        msg.Reason = make([]byte, minimumFailReasonLength)
1✔
2270
                        _, err := crand.Read(msg.Reason[:])
1✔
2271
                        if err != nil {
1✔
2272
                                l.log.Errorf("Random generation error: %v", err)
×
2273

×
2274
                                return
×
2275
                        }
×
2276
                }
2277

2278
                // Add fail to the update log.
2279
                idx := msg.ID
124✔
2280
                err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
124✔
2281
                if err != nil {
124✔
2282
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2283
                                "unable to handle upstream fail HTLC: %v", err)
×
2284
                        return
×
2285
                }
×
2286

2287
        case *lnwire.CommitSig:
1,211✔
2288
                // Since we may have learned new preimages for the first time,
1,211✔
2289
                // we'll add them to our preimage cache. By doing this, we
1,211✔
2290
                // ensure any contested contracts watched by any on-chain
1,211✔
2291
                // arbitrators can now sweep this HTLC on-chain. We delay
1,211✔
2292
                // committing the preimages until just before accepting the new
1,211✔
2293
                // remote commitment, as afterwards the peer won't resend the
1,211✔
2294
                // Settle messages on the next channel reestablishment. Doing so
1,211✔
2295
                // allows us to more effectively batch this operation, instead
1,211✔
2296
                // of doing a single write per preimage.
1,211✔
2297
                err := l.cfg.PreimageCache.AddPreimages(
1,211✔
2298
                        l.uncommittedPreimages...,
1,211✔
2299
                )
1,211✔
2300
                if err != nil {
1,211✔
2301
                        l.failf(
×
2302
                                LinkFailureError{code: ErrInternalError},
×
2303
                                "unable to add preimages=%v to cache: %v",
×
2304
                                l.uncommittedPreimages, err,
×
2305
                        )
×
2306
                        return
×
2307
                }
×
2308

2309
                // Instead of truncating the slice to conserve memory
2310
                // allocations, we simply set the uncommitted preimage slice to
2311
                // nil so that a new one will be initialized if any more
2312
                // witnesses are discovered. We do this because the maximum size
2313
                // that the slice can occupy is 15KB, and we want to ensure we
2314
                // release that memory back to the runtime.
2315
                l.uncommittedPreimages = nil
1,211✔
2316

1,211✔
2317
                // We just received a new updates to our local commitment
1,211✔
2318
                // chain, validate this new commitment, closing the link if
1,211✔
2319
                // invalid.
1,211✔
2320
                auxSigBlob, err := msg.CustomRecords.Serialize()
1,211✔
2321
                if err != nil {
1,211✔
2322
                        l.failf(
×
2323
                                LinkFailureError{code: ErrInvalidCommitment},
×
2324
                                "unable to serialize custom records: %v", err,
×
2325
                        )
×
2326

×
2327
                        return
×
2328
                }
×
2329
                err = l.channel.ReceiveNewCommitment(&lnwallet.CommitSigs{
1,211✔
2330
                        CommitSig:  msg.CommitSig,
1,211✔
2331
                        HtlcSigs:   msg.HtlcSigs,
1,211✔
2332
                        PartialSig: msg.PartialSig,
1,211✔
2333
                        AuxSigBlob: auxSigBlob,
1,211✔
2334
                })
1,211✔
2335
                if err != nil {
1,211✔
2336
                        // If we were unable to reconstruct their proposed
×
2337
                        // commitment, then we'll examine the type of error. If
×
2338
                        // it's an InvalidCommitSigError, then we'll send a
×
2339
                        // direct error.
×
2340
                        var sendData []byte
×
2341
                        switch err.(type) {
×
2342
                        case *lnwallet.InvalidCommitSigError:
×
2343
                                sendData = []byte(err.Error())
×
2344
                        case *lnwallet.InvalidHtlcSigError:
×
2345
                                sendData = []byte(err.Error())
×
2346
                        }
2347
                        l.failf(
×
2348
                                LinkFailureError{
×
2349
                                        code:          ErrInvalidCommitment,
×
2350
                                        FailureAction: LinkFailureForceClose,
×
2351
                                        SendData:      sendData,
×
2352
                                },
×
2353
                                "ChannelPoint(%v): unable to accept new "+
×
2354
                                        "commitment: %v",
×
2355
                                l.channel.ChannelPoint(), err,
×
2356
                        )
×
2357
                        return
×
2358
                }
2359

2360
                // As we've just accepted a new state, we'll now
2361
                // immediately send the remote peer a revocation for our prior
2362
                // state.
2363
                nextRevocation, currentHtlcs, finalHTLCs, err :=
1,211✔
2364
                        l.channel.RevokeCurrentCommitment()
1,211✔
2365
                if err != nil {
1,211✔
2366
                        l.log.Errorf("unable to revoke commitment: %v", err)
×
2367

×
2368
                        // We need to fail the channel in case revoking our
×
2369
                        // local commitment does not succeed. We might have
×
2370
                        // already advanced our channel state which would lead
×
2371
                        // us to proceed with an unclean state.
×
2372
                        //
×
2373
                        // NOTE: We do not trigger a force close because this
×
2374
                        // could resolve itself in case our db was just busy
×
2375
                        // not accepting new transactions.
×
2376
                        l.failf(
×
2377
                                LinkFailureError{
×
2378
                                        code:          ErrInternalError,
×
2379
                                        Warning:       true,
×
2380
                                        FailureAction: LinkFailureDisconnect,
×
2381
                                },
×
2382
                                "ChannelPoint(%v): unable to accept new "+
×
2383
                                        "commitment: %v",
×
2384
                                l.channel.ChannelPoint(), err,
×
2385
                        )
×
2386
                        return
×
2387
                }
×
2388

2389
                // As soon as we are ready to send our next revocation, we can
2390
                // invoke the incoming commit hooks.
2391
                l.RWMutex.Lock()
1,211✔
2392
                l.incomingCommitHooks.invoke()
1,211✔
2393
                l.RWMutex.Unlock()
1,211✔
2394

1,211✔
2395
                l.cfg.Peer.SendMessage(false, nextRevocation)
1,211✔
2396

1,211✔
2397
                // Notify the incoming htlcs of which the resolutions were
1,211✔
2398
                // locked in.
1,211✔
2399
                for id, settled := range finalHTLCs {
1,546✔
2400
                        l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
335✔
2401
                                models.CircuitKey{
335✔
2402
                                        ChanID: l.ShortChanID(),
335✔
2403
                                        HtlcID: id,
335✔
2404
                                },
335✔
2405
                                channeldb.FinalHtlcInfo{
335✔
2406
                                        Settled:  settled,
335✔
2407
                                        Offchain: true,
335✔
2408
                                },
335✔
2409
                        )
335✔
2410
                }
335✔
2411

2412
                // Since we just revoked our commitment, we may have a new set
2413
                // of HTLC's on our commitment, so we'll send them using our
2414
                // function closure NotifyContractUpdate.
2415
                newUpdate := &contractcourt.ContractUpdate{
1,211✔
2416
                        HtlcKey: contractcourt.LocalHtlcSet,
1,211✔
2417
                        Htlcs:   currentHtlcs,
1,211✔
2418
                }
1,211✔
2419
                err = l.cfg.NotifyContractUpdate(newUpdate)
1,211✔
2420
                if err != nil {
1,211✔
2421
                        l.log.Errorf("unable to notify contract update: %v",
×
2422
                                err)
×
2423
                        return
×
2424
                }
×
2425

2426
                select {
1,211✔
NEW
2427
                case <-l.cg.Done():
×
2428
                        return
×
2429
                default:
1,211✔
2430
                }
2431

2432
                // If the remote party initiated the state transition,
2433
                // we'll reply with a signature to provide them with their
2434
                // version of the latest commitment. Otherwise, both commitment
2435
                // chains are fully synced from our PoV, then we don't need to
2436
                // reply with a signature as both sides already have a
2437
                // commitment with the latest accepted.
2438
                if l.channel.OweCommitment() {
1,890✔
2439
                        if !l.updateCommitTxOrFail(ctx) {
679✔
2440
                                return
×
2441
                        }
×
2442
                }
2443

2444
                // If we need to send out an Stfu, this would be the time to do
2445
                // so.
2446
                if l.noDanglingUpdates(lntypes.Local) {
2,280✔
2447
                        err = l.quiescer.SendOwedStfu()
1,069✔
2448
                        if err != nil {
1,069✔
2449
                                l.stfuFailf("sendOwedStfu: %v", err.Error())
×
2450
                        }
×
2451
                }
2452

2453
                // Now that we have finished processing the incoming CommitSig
2454
                // and sent out our RevokeAndAck, we invoke the flushHooks if
2455
                // the channel state is clean.
2456
                l.RWMutex.Lock()
1,211✔
2457
                if l.channel.IsChannelClean() {
1,391✔
2458
                        l.flushHooks.invoke()
180✔
2459
                }
180✔
2460
                l.RWMutex.Unlock()
1,211✔
2461

2462
        case *lnwire.RevokeAndAck:
1,200✔
2463
                // We've received a revocation from the remote chain, if valid,
1,200✔
2464
                // this moves the remote chain forward, and expands our
1,200✔
2465
                // revocation window.
1,200✔
2466

1,200✔
2467
                // We now process the message and advance our remote commit
1,200✔
2468
                // chain.
1,200✔
2469
                fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
1,200✔
2470
                if err != nil {
1,200✔
2471
                        // TODO(halseth): force close?
×
2472
                        l.failf(
×
2473
                                LinkFailureError{
×
2474
                                        code:          ErrInvalidRevocation,
×
2475
                                        FailureAction: LinkFailureDisconnect,
×
2476
                                },
×
2477
                                "unable to accept revocation: %v", err,
×
2478
                        )
×
2479
                        return
×
2480
                }
×
2481

2482
                // The remote party now has a new primary commitment, so we'll
2483
                // update the contract court to be aware of this new set (the
2484
                // prior old remote pending).
2485
                newUpdate := &contractcourt.ContractUpdate{
1,200✔
2486
                        HtlcKey: contractcourt.RemoteHtlcSet,
1,200✔
2487
                        Htlcs:   remoteHTLCs,
1,200✔
2488
                }
1,200✔
2489
                err = l.cfg.NotifyContractUpdate(newUpdate)
1,200✔
2490
                if err != nil {
1,200✔
2491
                        l.log.Errorf("unable to notify contract update: %v",
×
2492
                                err)
×
2493
                        return
×
2494
                }
×
2495

2496
                select {
1,200✔
2497
                case <-l.cg.Done():
2✔
2498
                        return
2✔
2499
                default:
1,198✔
2500
                }
2501

2502
                // If we have a tower client for this channel type, we'll
2503
                // create a backup for the current state.
2504
                if l.cfg.TowerClient != nil {
1,202✔
2505
                        state := l.channel.State()
4✔
2506
                        chanID := l.ChanID()
4✔
2507

4✔
2508
                        err = l.cfg.TowerClient.BackupState(
4✔
2509
                                &chanID, state.RemoteCommitment.CommitHeight-1,
4✔
2510
                        )
4✔
2511
                        if err != nil {
4✔
2512
                                l.failf(LinkFailureError{
×
2513
                                        code: ErrInternalError,
×
2514
                                }, "unable to queue breach backup: %v", err)
×
2515
                                return
×
2516
                        }
×
2517
                }
2518

2519
                // If we can send updates then we can process adds in case we
2520
                // are the exit hop and need to send back resolutions, or in
2521
                // case there are validity issues with the packets. Otherwise
2522
                // we defer the action until resume.
2523
                //
2524
                // We are free to process the settles and fails without this
2525
                // check since processing those can't result in further updates
2526
                // to this channel link.
2527
                if l.quiescer.CanSendUpdates() {
2,395✔
2528
                        l.processRemoteAdds(fwdPkg)
1,197✔
2529
                } else {
1,198✔
2530
                        l.quiescer.OnResume(func() {
1✔
2531
                                l.processRemoteAdds(fwdPkg)
×
2532
                        })
×
2533
                }
2534
                l.processRemoteSettleFails(fwdPkg)
1,198✔
2535

1,198✔
2536
                // If the link failed during processing the adds, we must
1,198✔
2537
                // return to ensure we won't attempted to update the state
1,198✔
2538
                // further.
1,198✔
2539
                if l.failed {
1,202✔
2540
                        return
4✔
2541
                }
4✔
2542

2543
                // The revocation window opened up. If there are pending local
2544
                // updates, try to update the commit tx. Pending updates could
2545
                // already have been present because of a previously failed
2546
                // update to the commit tx or freshly added in by
2547
                // processRemoteAdds. Also in case there are no local updates,
2548
                // but there are still remote updates that are not in the remote
2549
                // commit tx yet, send out an update.
2550
                if l.channel.OweCommitment() {
1,530✔
2551
                        if !l.updateCommitTxOrFail(ctx) {
339✔
2552
                                return
7✔
2553
                        }
7✔
2554
                }
2555

2556
                // Now that we have finished processing the RevokeAndAck, we
2557
                // can invoke the flushHooks if the channel state is clean.
2558
                l.RWMutex.Lock()
1,191✔
2559
                if l.channel.IsChannelClean() {
1,354✔
2560
                        l.flushHooks.invoke()
163✔
2561
                }
163✔
2562
                l.RWMutex.Unlock()
1,191✔
2563

2564
        case *lnwire.UpdateFee:
3✔
2565
                // Check and see if their proposed fee-rate would make us
3✔
2566
                // exceed the fee threshold.
3✔
2567
                fee := chainfee.SatPerKWeight(msg.FeePerKw)
3✔
2568

3✔
2569
                isDust, err := l.exceedsFeeExposureLimit(fee)
3✔
2570
                if err != nil {
3✔
2571
                        // This shouldn't typically happen. If it does, it
×
2572
                        // indicates something is wrong with our channel state.
×
2573
                        l.log.Errorf("Unable to determine if fee threshold " +
×
2574
                                "exceeded")
×
2575
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2576
                                "error calculating fee exposure: %v", err)
×
2577

×
2578
                        return
×
2579
                }
×
2580

2581
                if isDust {
3✔
2582
                        // The proposed fee-rate makes us exceed the fee
×
2583
                        // threshold.
×
2584
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2585
                                "fee threshold exceeded: %v", err)
×
2586
                        return
×
2587
                }
×
2588

2589
                // We received fee update from peer. If we are the initiator we
2590
                // will fail the channel, if not we will apply the update.
2591
                if err := l.channel.ReceiveUpdateFee(fee); err != nil {
3✔
2592
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2593
                                "error receiving fee update: %v", err)
×
2594
                        return
×
2595
                }
×
2596

2597
                // Update the mailbox's feerate as well.
2598
                l.mailBox.SetFeeRate(fee)
3✔
2599

2600
        case *lnwire.Stfu:
6✔
2601
                err := l.handleStfu(msg)
6✔
2602
                if err != nil {
6✔
2603
                        l.stfuFailf("handleStfu: %v", err.Error())
×
2604
                }
×
2605

2606
        // In the case where we receive a warning message from our peer, just
2607
        // log it and move on. We choose not to disconnect from our peer,
2608
        // although we "MAY" do so according to the specification.
2609
        case *lnwire.Warning:
1✔
2610
                l.log.Warnf("received warning message from peer: %v",
1✔
2611
                        msg.Warning())
1✔
2612

2613
        case *lnwire.Error:
4✔
2614
                // Error received from remote, MUST fail channel, but should
4✔
2615
                // only print the contents of the error message if all
4✔
2616
                // characters are printable ASCII.
4✔
2617
                l.failf(
4✔
2618
                        LinkFailureError{
4✔
2619
                                code: ErrRemoteError,
4✔
2620

4✔
2621
                                // TODO(halseth): we currently don't fail the
4✔
2622
                                // channel permanently, as there are some sync
4✔
2623
                                // issues with other implementations that will
4✔
2624
                                // lead to them sending an error message, but
4✔
2625
                                // we can recover from on next connection. See
4✔
2626
                                // https://github.com/ElementsProject/lightning/issues/4212
4✔
2627
                                PermanentFailure: false,
4✔
2628
                        },
4✔
2629
                        "ChannelPoint(%v): received error from peer: %v",
4✔
2630
                        l.channel.ChannelPoint(), msg.Error(),
4✔
2631
                )
4✔
2632
        default:
×
2633
                l.log.Warnf("received unknown message of type %T", msg)
×
2634
        }
2635

2636
}
2637

2638
// handleStfu implements the top-level logic for handling the Stfu message from
2639
// our peer.
2640
func (l *channelLink) handleStfu(stfu *lnwire.Stfu) error {
6✔
2641
        if !l.noDanglingUpdates(lntypes.Remote) {
6✔
2642
                return ErrPendingRemoteUpdates
×
2643
        }
×
2644
        err := l.quiescer.RecvStfu(*stfu)
6✔
2645
        if err != nil {
6✔
2646
                return err
×
2647
        }
×
2648

2649
        // If we can immediately send an Stfu response back, we will.
2650
        if l.noDanglingUpdates(lntypes.Local) {
11✔
2651
                return l.quiescer.SendOwedStfu()
5✔
2652
        }
5✔
2653

2654
        return nil
1✔
2655
}
2656

2657
// stfuFailf fails the link in the case where the requirements of the quiescence
2658
// protocol are violated. In all cases we opt to drop the connection as only
2659
// link state (as opposed to channel state) is affected.
2660
func (l *channelLink) stfuFailf(format string, args ...interface{}) {
×
2661
        l.failf(LinkFailureError{
×
2662
                code:             ErrStfuViolation,
×
2663
                FailureAction:    LinkFailureDisconnect,
×
2664
                PermanentFailure: false,
×
2665
                Warning:          true,
×
2666
        }, format, args...)
×
2667
}
×
2668

2669
// noDanglingUpdates returns true when there are 0 updates that were originally
2670
// issued by whose on either the Local or Remote commitment transaction.
2671
func (l *channelLink) noDanglingUpdates(whose lntypes.ChannelParty) bool {
1,216✔
2672
        pendingOnLocal := l.channel.NumPendingUpdates(
1,216✔
2673
                whose, lntypes.Local,
1,216✔
2674
        )
1,216✔
2675
        pendingOnRemote := l.channel.NumPendingUpdates(
1,216✔
2676
                whose, lntypes.Remote,
1,216✔
2677
        )
1,216✔
2678

1,216✔
2679
        return pendingOnLocal == 0 && pendingOnRemote == 0
1,216✔
2680
}
1,216✔
2681

2682
// ackDownStreamPackets is responsible for removing htlcs from a link's mailbox
2683
// for packets delivered from server, and cleaning up any circuits closed by
2684
// signing a previous commitment txn. This method ensures that the circuits are
2685
// removed from the circuit map before removing them from the link's mailbox,
2686
// otherwise it could be possible for some circuit to be missed if this link
2687
// flaps.
2688
func (l *channelLink) ackDownStreamPackets() error {
1,390✔
2689
        // First, remove the downstream Add packets that were included in the
1,390✔
2690
        // previous commitment signature. This will prevent the Adds from being
1,390✔
2691
        // replayed if this link disconnects.
1,390✔
2692
        for _, inKey := range l.openedCircuits {
1,858✔
2693
                // In order to test the sphinx replay logic of the remote
468✔
2694
                // party, unsafe replay does not acknowledge the packets from
468✔
2695
                // the mailbox. We can then force a replay of any Add packets
468✔
2696
                // held in memory by disconnecting and reconnecting the link.
468✔
2697
                if l.cfg.UnsafeReplay {
472✔
2698
                        continue
4✔
2699
                }
2700

2701
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
468✔
2702
                l.mailBox.AckPacket(inKey)
468✔
2703
        }
2704

2705
        // Now, we will delete all circuits closed by the previous commitment
2706
        // signature, which is the result of downstream Settle/Fail packets. We
2707
        // batch them here to ensure circuits are closed atomically and for
2708
        // performance.
2709
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
1,390✔
2710
        switch err {
1,390✔
2711
        case nil:
1,390✔
2712
                // Successful deletion.
2713

2714
        default:
×
2715
                l.log.Errorf("unable to delete %d circuits: %v",
×
2716
                        len(l.closedCircuits), err)
×
2717
                return err
×
2718
        }
2719

2720
        // With the circuits removed from memory and disk, we now ack any
2721
        // Settle/Fails in the mailbox to ensure they do not get redelivered
2722
        // after startup. If forgive is enabled and we've reached this point,
2723
        // the circuits must have been removed at some point, so it is now safe
2724
        // to un-queue the corresponding Settle/Fails.
2725
        for _, inKey := range l.closedCircuits {
1,433✔
2726
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
43✔
2727
                        inKey)
43✔
2728
                l.mailBox.AckPacket(inKey)
43✔
2729
        }
43✔
2730

2731
        // Lastly, reset our buffers to be empty while keeping any acquired
2732
        // growth in the backing array.
2733
        l.openedCircuits = l.openedCircuits[:0]
1,390✔
2734
        l.closedCircuits = l.closedCircuits[:0]
1,390✔
2735

1,390✔
2736
        return nil
1,390✔
2737
}
2738

2739
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
2740
// the link.
2741
func (l *channelLink) updateCommitTxOrFail(ctx context.Context) bool {
1,253✔
2742
        err := l.updateCommitTx(ctx)
1,253✔
2743
        switch err {
1,253✔
2744
        // No error encountered, success.
2745
        case nil:
1,243✔
2746

2747
        // A duplicate keystone error should be resolved and is not fatal, so
2748
        // we won't send an Error message to the peer.
2749
        case ErrDuplicateKeystone:
×
2750
                l.failf(LinkFailureError{code: ErrCircuitError},
×
2751
                        "temporary circuit error: %v", err)
×
2752
                return false
×
2753

2754
        // Any other error is treated results in an Error message being sent to
2755
        // the peer.
2756
        default:
10✔
2757
                l.failf(LinkFailureError{code: ErrInternalError},
10✔
2758
                        "unable to update commitment: %v", err)
10✔
2759
                return false
10✔
2760
        }
2761

2762
        return true
1,243✔
2763
}
2764

2765
// updateCommitTx signs, then sends an update to the remote peer adding a new
2766
// commitment to their commitment chain which includes all the latest updates
2767
// we've received+processed up to this point.
2768
func (l *channelLink) updateCommitTx(ctx context.Context) error {
1,311✔
2769
        // Preemptively write all pending keystones to disk, just in case the
1,311✔
2770
        // HTLCs we have in memory are included in the subsequent attempt to
1,311✔
2771
        // sign a commitment state.
1,311✔
2772
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
1,311✔
2773
        if err != nil {
1,311✔
2774
                // If ErrDuplicateKeystone is returned, the caller will catch
×
2775
                // it.
×
2776
                return err
×
2777
        }
×
2778

2779
        // Reset the batch, but keep the backing buffer to avoid reallocating.
2780
        l.keystoneBatch = l.keystoneBatch[:0]
1,311✔
2781

1,311✔
2782
        // If hodl.Commit mode is active, we will refrain from attempting to
1,311✔
2783
        // commit any in-memory modifications to the channel state. Exiting here
1,311✔
2784
        // permits testing of either the switch or link's ability to trim
1,311✔
2785
        // circuits that have been opened, but unsuccessfully committed.
1,311✔
2786
        if l.cfg.HodlMask.Active(hodl.Commit) {
1,319✔
2787
                l.log.Warnf(hodl.Commit.Warning())
8✔
2788
                return nil
8✔
2789
        }
8✔
2790

2791
        ctx, done := l.cg.Create(ctx)
1,307✔
2792
        defer done()
1,307✔
2793

1,307✔
2794
        newCommit, err := l.channel.SignNextCommitment(ctx)
1,307✔
2795
        if err == lnwallet.ErrNoWindow {
1,398✔
2796
                l.cfg.PendingCommitTicker.Resume()
91✔
2797
                l.log.Trace("PendingCommitTicker resumed")
91✔
2798

91✔
2799
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
91✔
2800
                l.log.Tracef("revocation window exhausted, unable to send: "+
91✔
2801
                        "%v, pend_updates=%v, dangling_closes%v", n,
91✔
2802
                        lnutils.SpewLogClosure(l.openedCircuits),
91✔
2803
                        lnutils.SpewLogClosure(l.closedCircuits))
91✔
2804

91✔
2805
                return nil
91✔
2806
        } else if err != nil {
1,311✔
2807
                return err
×
2808
        }
×
2809

2810
        if err := l.ackDownStreamPackets(); err != nil {
1,220✔
2811
                return err
×
2812
        }
×
2813

2814
        l.cfg.PendingCommitTicker.Pause()
1,220✔
2815
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
1,220✔
2816

1,220✔
2817
        // The remote party now has a new pending commitment, so we'll update
1,220✔
2818
        // the contract court to be aware of this new set (the prior old remote
1,220✔
2819
        // pending).
1,220✔
2820
        newUpdate := &contractcourt.ContractUpdate{
1,220✔
2821
                HtlcKey: contractcourt.RemotePendingHtlcSet,
1,220✔
2822
                Htlcs:   newCommit.PendingHTLCs,
1,220✔
2823
        }
1,220✔
2824
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,220✔
2825
        if err != nil {
1,220✔
2826
                l.log.Errorf("unable to notify contract update: %v", err)
×
2827
                return err
×
2828
        }
×
2829

2830
        select {
1,220✔
2831
        case <-l.cg.Done():
11✔
2832
                return ErrLinkShuttingDown
11✔
2833
        default:
1,209✔
2834
        }
2835

2836
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
1,209✔
2837
        if err != nil {
1,209✔
2838
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
2839
        }
×
2840

2841
        commitSig := &lnwire.CommitSig{
1,209✔
2842
                ChanID:        l.ChanID(),
1,209✔
2843
                CommitSig:     newCommit.CommitSig,
1,209✔
2844
                HtlcSigs:      newCommit.HtlcSigs,
1,209✔
2845
                PartialSig:    newCommit.PartialSig,
1,209✔
2846
                CustomRecords: auxBlobRecords,
1,209✔
2847
        }
1,209✔
2848
        l.cfg.Peer.SendMessage(false, commitSig)
1,209✔
2849

1,209✔
2850
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
1,209✔
2851
        // of commit hooks.
1,209✔
2852
        l.RWMutex.Lock()
1,209✔
2853
        l.outgoingCommitHooks.invoke()
1,209✔
2854
        l.RWMutex.Unlock()
1,209✔
2855

1,209✔
2856
        return nil
1,209✔
2857
}
2858

2859
// Peer returns the representation of remote peer with which we have the
2860
// channel link opened.
2861
//
2862
// NOTE: Part of the ChannelLink interface.
2863
func (l *channelLink) PeerPubKey() [33]byte {
445✔
2864
        return l.cfg.Peer.PubKey()
445✔
2865
}
445✔
2866

2867
// ChannelPoint returns the channel outpoint for the channel link.
2868
// NOTE: Part of the ChannelLink interface.
2869
func (l *channelLink) ChannelPoint() wire.OutPoint {
856✔
2870
        return l.channel.ChannelPoint()
856✔
2871
}
856✔
2872

2873
// ShortChanID returns the short channel ID for the channel link. The short
2874
// channel ID encodes the exact location in the main chain that the original
2875
// funding output can be found.
2876
//
2877
// NOTE: Part of the ChannelLink interface.
2878
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
4,252✔
2879
        l.RLock()
4,252✔
2880
        defer l.RUnlock()
4,252✔
2881

4,252✔
2882
        return l.channel.ShortChanID()
4,252✔
2883
}
4,252✔
2884

2885
// UpdateShortChanID updates the short channel ID for a link. This may be
2886
// required in the event that a link is created before the short chan ID for it
2887
// is known, or a re-org occurs, and the funding transaction changes location
2888
// within the chain.
2889
//
2890
// NOTE: Part of the ChannelLink interface.
2891
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
4✔
2892
        chanID := l.ChanID()
4✔
2893

4✔
2894
        // Refresh the channel state's short channel ID by loading it from disk.
4✔
2895
        // This ensures that the channel state accurately reflects the updated
4✔
2896
        // short channel ID.
4✔
2897
        err := l.channel.State().Refresh()
4✔
2898
        if err != nil {
4✔
2899
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
2900
                        "%v", chanID, err)
×
2901
                return hop.Source, err
×
2902
        }
×
2903

2904
        return hop.Source, nil
4✔
2905
}
2906

2907
// ChanID returns the channel ID for the channel link. The channel ID is a more
2908
// compact representation of a channel's full outpoint.
2909
//
2910
// NOTE: Part of the ChannelLink interface.
2911
func (l *channelLink) ChanID() lnwire.ChannelID {
3,949✔
2912
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
3,949✔
2913
}
3,949✔
2914

2915
// Bandwidth returns the total amount that can flow through the channel link at
2916
// this given instance. The value returned is expressed in millisatoshi and can
2917
// be used by callers when making forwarding decisions to determine if a link
2918
// can accept an HTLC.
2919
//
2920
// NOTE: Part of the ChannelLink interface.
2921
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
816✔
2922
        // Get the balance available on the channel for new HTLCs. This takes
816✔
2923
        // the channel reserve into account so HTLCs up to this value won't
816✔
2924
        // violate it.
816✔
2925
        return l.channel.AvailableBalance()
816✔
2926
}
816✔
2927

2928
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2929
// amount provided to the link. This check does not reserve a space, since
2930
// forwards or other payments may use the available slot, so it should be
2931
// considered best-effort.
2932
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
4✔
2933
        return l.channel.MayAddOutgoingHtlc(amt)
4✔
2934
}
4✔
2935

2936
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2937
// method.
2938
//
2939
// NOTE: Part of the dustHandler interface.
2940
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2941
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
2,527✔
2942

2,527✔
2943
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
2,527✔
2944
}
2,527✔
2945

2946
// getFeeRate is a wrapper method that retrieves the underlying channel's
2947
// feerate.
2948
//
2949
// NOTE: Part of the dustHandler interface.
2950
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
673✔
2951
        return l.channel.CommitFeeRate()
673✔
2952
}
673✔
2953

2954
// getDustClosure returns a closure that can be used by the switch or mailbox
2955
// to evaluate whether a given HTLC is dust.
2956
//
2957
// NOTE: Part of the dustHandler interface.
2958
func (l *channelLink) getDustClosure() dustClosure {
1,603✔
2959
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
1,603✔
2960
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
1,603✔
2961
        chanType := l.channel.State().ChanType
1,603✔
2962

1,603✔
2963
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
1,603✔
2964
}
1,603✔
2965

2966
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2967
// is used so that the Switch can have access to the commitment fee without
2968
// needing to have a *LightningChannel. This doesn't include dust.
2969
//
2970
// NOTE: Part of the dustHandler interface.
2971
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
1,890✔
2972
        if remote {
2,850✔
2973
                return l.channel.State().RemoteCommitment.CommitFee
960✔
2974
        }
960✔
2975

2976
        return l.channel.State().LocalCommitment.CommitFee
934✔
2977
}
2978

2979
// exceedsFeeExposureLimit returns whether or not the new proposed fee-rate
2980
// increases the total dust and fees within the channel past the configured
2981
// fee threshold. It first calculates the dust sum over every update in the
2982
// update log with the proposed fee-rate and taking into account both the local
2983
// and remote dust limits. It uses every update in the update log instead of
2984
// what is actually on the local and remote commitments because it is assumed
2985
// that in a worst-case scenario, every update in the update log could
2986
// theoretically be on either commitment transaction and this needs to be
2987
// accounted for with this fee-rate. It then calculates the local and remote
2988
// commitment fees given the proposed fee-rate. Finally, it tallies the results
2989
// and determines if the fee threshold has been exceeded.
2990
func (l *channelLink) exceedsFeeExposureLimit(
2991
        feePerKw chainfee.SatPerKWeight) (bool, error) {
6✔
2992

6✔
2993
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
6✔
2994

6✔
2995
        // Get the sum of dust for both the local and remote commitments using
6✔
2996
        // this "dry-run" fee.
6✔
2997
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
6✔
2998
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
6✔
2999

6✔
3000
        // Calculate the local and remote commitment fees using this dry-run
6✔
3001
        // fee.
6✔
3002
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
3003
        if err != nil {
6✔
3004
                return false, err
×
3005
        }
×
3006

3007
        // Finally, check whether the max fee exposure was exceeded on either
3008
        // future commitment transaction with the fee-rate.
3009
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
6✔
3010
        if totalLocalDust > l.cfg.MaxFeeExposure {
6✔
3011
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
3012
                        "local dust: %v, local fee: %v", l.ShortChanID(),
×
3013
                        totalLocalDust, localFee)
×
3014

×
3015
                return true, nil
×
3016
        }
×
3017

3018
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
6✔
3019
                remoteFee,
6✔
3020
        )
6✔
3021

6✔
3022
        if totalRemoteDust > l.cfg.MaxFeeExposure {
6✔
3023
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
3024
                        "remote dust: %v, remote fee: %v", l.ShortChanID(),
×
3025
                        totalRemoteDust, remoteFee)
×
3026

×
3027
                return true, nil
×
3028
        }
×
3029

3030
        return false, nil
6✔
3031
}
3032

3033
// isOverexposedWithHtlc calculates whether the proposed HTLC will make the
3034
// channel exceed the fee threshold. It first fetches the largest fee-rate that
3035
// may be on any unrevoked commitment transaction. Then, using this fee-rate,
3036
// determines if the to-be-added HTLC is dust. If the HTLC is dust, it adds to
3037
// the overall dust sum. If it is not dust, it contributes to weight, which
3038
// also adds to the overall dust sum by an increase in fees. If the dust sum on
3039
// either commitment exceeds the configured fee threshold, this function
3040
// returns true.
3041
func (l *channelLink) isOverexposedWithHtlc(htlc *lnwire.UpdateAddHTLC,
3042
        incoming bool) bool {
934✔
3043

934✔
3044
        dustClosure := l.getDustClosure()
934✔
3045

934✔
3046
        feeRate := l.channel.WorstCaseFeeRate()
934✔
3047

934✔
3048
        amount := htlc.Amount.ToSatoshis()
934✔
3049

934✔
3050
        // See if this HTLC is dust on both the local and remote commitments.
934✔
3051
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
934✔
3052
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
934✔
3053

934✔
3054
        // Calculate the dust sum for the local and remote commitments.
934✔
3055
        localDustSum := l.getDustSum(
934✔
3056
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
934✔
3057
        )
934✔
3058
        remoteDustSum := l.getDustSum(
934✔
3059
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
934✔
3060
        )
934✔
3061

934✔
3062
        // Grab the larger of the local and remote commitment fees w/o dust.
934✔
3063
        commitFee := l.getCommitFee(false)
934✔
3064

934✔
3065
        if l.getCommitFee(true) > commitFee {
964✔
3066
                commitFee = l.getCommitFee(true)
30✔
3067
        }
30✔
3068

3069
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
934✔
3070

934✔
3071
        localDustSum += commitFeeMSat
934✔
3072
        remoteDustSum += commitFeeMSat
934✔
3073

934✔
3074
        // Calculate the additional fee increase if this is a non-dust HTLC.
934✔
3075
        weight := lntypes.WeightUnit(input.HTLCWeight)
934✔
3076
        additional := lnwire.NewMSatFromSatoshis(
934✔
3077
                feeRate.FeeForWeight(weight),
934✔
3078
        )
934✔
3079

934✔
3080
        if isLocalDust {
1,571✔
3081
                // If this is dust, it doesn't contribute to weight but does
637✔
3082
                // contribute to the overall dust sum.
637✔
3083
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
637✔
3084
        } else {
938✔
3085
                // Account for the fee increase that comes with an increase in
301✔
3086
                // weight.
301✔
3087
                localDustSum += additional
301✔
3088
        }
301✔
3089

3090
        if localDustSum > l.cfg.MaxFeeExposure {
938✔
3091
                // The max fee exposure was exceeded.
4✔
3092
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
4✔
3093
                        "overexposed, total local dust: %v (current commit "+
4✔
3094
                        "fee: %v)", l.ShortChanID(), htlc, localDustSum)
4✔
3095

4✔
3096
                return true
4✔
3097
        }
4✔
3098

3099
        if isRemoteDust {
1,564✔
3100
                // If this is dust, it doesn't contribute to weight but does
634✔
3101
                // contribute to the overall dust sum.
634✔
3102
                remoteDustSum += lnwire.NewMSatFromSatoshis(amount)
634✔
3103
        } else {
934✔
3104
                // Account for the fee increase that comes with an increase in
300✔
3105
                // weight.
300✔
3106
                remoteDustSum += additional
300✔
3107
        }
300✔
3108

3109
        if remoteDustSum > l.cfg.MaxFeeExposure {
930✔
3110
                // The max fee exposure was exceeded.
×
3111
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
3112
                        "overexposed, total remote dust: %v (current commit "+
×
3113
                        "fee: %v)", l.ShortChanID(), htlc, remoteDustSum)
×
3114

×
3115
                return true
×
3116
        }
×
3117

3118
        return false
930✔
3119
}
3120

3121
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
3122
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
3123
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
3124
// whether to evaluate on the local or remote commit, and finally an HTLC
3125
// amount to test.
3126
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
3127
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
3128

3129
// dustHelper is used to construct the dustClosure.
3130
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
3131
        remoteDustLimit btcutil.Amount) dustClosure {
1,803✔
3132

1,803✔
3133
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
1,803✔
3134
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
11,263✔
3135

9,460✔
3136
                var dustLimit btcutil.Amount
9,460✔
3137
                if whoseCommit.IsLocal() {
14,192✔
3138
                        dustLimit = localDustLimit
4,732✔
3139
                } else {
9,464✔
3140
                        dustLimit = remoteDustLimit
4,732✔
3141
                }
4,732✔
3142

3143
                return lnwallet.HtlcIsDust(
9,460✔
3144
                        chantype, incoming, whoseCommit, feerate, amt,
9,460✔
3145
                        dustLimit,
9,460✔
3146
                )
9,460✔
3147
        }
3148

3149
        return isDust
1,803✔
3150
}
3151

3152
// zeroConfConfirmed returns whether or not the zero-conf channel has
3153
// confirmed on-chain.
3154
//
3155
// Part of the scidAliasHandler interface.
3156
func (l *channelLink) zeroConfConfirmed() bool {
7✔
3157
        return l.channel.State().ZeroConfConfirmed()
7✔
3158
}
7✔
3159

3160
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
3161
// should not be called for non-zero-conf channels.
3162
//
3163
// Part of the scidAliasHandler interface.
3164
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
7✔
3165
        return l.channel.State().ZeroConfRealScid()
7✔
3166
}
7✔
3167

3168
// isZeroConf returns whether or not the underlying channel is a zero-conf
3169
// channel.
3170
//
3171
// Part of the scidAliasHandler interface.
3172
func (l *channelLink) isZeroConf() bool {
217✔
3173
        return l.channel.State().IsZeroConf()
217✔
3174
}
217✔
3175

3176
// negotiatedAliasFeature returns whether or not the underlying channel has
3177
// negotiated the option-scid-alias feature bit. This will be true for both
3178
// option-scid-alias and zero-conf channel-types. It will also be true for
3179
// channels with the feature bit but without the above channel-types.
3180
//
3181
// Part of the scidAliasFeature interface.
3182
func (l *channelLink) negotiatedAliasFeature() bool {
378✔
3183
        return l.channel.State().NegotiatedAliasFeature()
378✔
3184
}
378✔
3185

3186
// getAliases returns the set of aliases for the underlying channel.
3187
//
3188
// Part of the scidAliasHandler interface.
3189
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
223✔
3190
        return l.cfg.GetAliases(l.ShortChanID())
223✔
3191
}
223✔
3192

3193
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
3194
//
3195
// Part of the scidAliasHandler interface.
3196
func (l *channelLink) attachFailAliasUpdate(closure func(
3197
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
218✔
3198

218✔
3199
        l.Lock()
218✔
3200
        l.cfg.FailAliasUpdate = closure
218✔
3201
        l.Unlock()
218✔
3202
}
218✔
3203

3204
// AttachMailBox updates the current mailbox used by this link, and hooks up
3205
// the mailbox's message and packet outboxes to the link's upstream and
3206
// downstream chans, respectively.
3207
func (l *channelLink) AttachMailBox(mailbox MailBox) {
217✔
3208
        l.Lock()
217✔
3209
        l.mailBox = mailbox
217✔
3210
        l.upstream = mailbox.MessageOutBox()
217✔
3211
        l.downstream = mailbox.PacketOutBox()
217✔
3212
        l.Unlock()
217✔
3213

217✔
3214
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
217✔
3215
        // never committed.
217✔
3216
        l.mailBox.SetFeeRate(l.getFeeRate())
217✔
3217

217✔
3218
        // Also set the mailbox's dust closure so that it can query whether HTLC's
217✔
3219
        // are dust given the current feerate.
217✔
3220
        l.mailBox.SetDustClosure(l.getDustClosure())
217✔
3221
}
217✔
3222

3223
// UpdateForwardingPolicy updates the forwarding policy for the target
3224
// ChannelLink. Once updated, the link will use the new forwarding policy to
3225
// govern if it an incoming HTLC should be forwarded or not. We assume that
3226
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
3227
// update all of the link's FwrdingPolicy's values.
3228
//
3229
// NOTE: Part of the ChannelLink interface.
3230
func (l *channelLink) UpdateForwardingPolicy(
3231
        newPolicy models.ForwardingPolicy) {
16✔
3232

16✔
3233
        l.Lock()
16✔
3234
        defer l.Unlock()
16✔
3235

16✔
3236
        l.cfg.FwrdingPolicy = newPolicy
16✔
3237
}
16✔
3238

3239
// CheckHtlcForward should return a nil error if the passed HTLC details
3240
// satisfy the current forwarding policy fo the target link. Otherwise,
3241
// a LinkError with a valid protocol failure message should be returned
3242
// in order to signal to the source of the HTLC, the policy consistency
3243
// issue.
3244
//
3245
// NOTE: Part of the ChannelLink interface.
3246
func (l *channelLink) CheckHtlcForward(payHash [32]byte, incomingHtlcAmt,
3247
        amtToForward lnwire.MilliSatoshi, incomingTimeout,
3248
        outgoingTimeout uint32, inboundFee models.InboundFee,
3249
        heightNow uint32, originalScid lnwire.ShortChannelID,
3250
        customRecords lnwire.CustomRecords) *LinkError {
53✔
3251

53✔
3252
        l.RLock()
53✔
3253
        policy := l.cfg.FwrdingPolicy
53✔
3254
        l.RUnlock()
53✔
3255

53✔
3256
        // Using the outgoing HTLC amount, we'll calculate the outgoing
53✔
3257
        // fee this incoming HTLC must carry in order to satisfy the constraints
53✔
3258
        // of the outgoing link.
53✔
3259
        outFee := ExpectedFee(policy, amtToForward)
53✔
3260

53✔
3261
        // Then calculate the inbound fee that we charge based on the sum of
53✔
3262
        // outgoing HTLC amount and outgoing fee.
53✔
3263
        inFee := inboundFee.CalcFee(amtToForward + outFee)
53✔
3264

53✔
3265
        // Add up both fee components. It is important to calculate both fees
53✔
3266
        // separately. An alternative way of calculating is to first determine
53✔
3267
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
53✔
3268
        // rounding may cause the result to be slightly higher than in the case
53✔
3269
        // of separately rounded fee components. This potentially causes failed
53✔
3270
        // forwards for senders and is something to be avoided.
53✔
3271
        expectedFee := inFee + int64(outFee)
53✔
3272

53✔
3273
        // If the actual fee is less than our expected fee, then we'll reject
53✔
3274
        // this HTLC as it didn't provide a sufficient amount of fees, or the
53✔
3275
        // values have been tampered with, or the send used incorrect/dated
53✔
3276
        // information to construct the forwarding information for this hop. In
53✔
3277
        // any case, we'll cancel this HTLC.
53✔
3278
        actualFee := int64(incomingHtlcAmt) - int64(amtToForward)
53✔
3279
        if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
63✔
3280
                l.log.Warnf("outgoing htlc(%x) has insufficient fee: "+
10✔
3281
                        "expected %v, got %v: incoming=%v, outgoing=%v, "+
10✔
3282
                        "inboundFee=%v",
10✔
3283
                        payHash[:], expectedFee, actualFee,
10✔
3284
                        incomingHtlcAmt, amtToForward, inboundFee,
10✔
3285
                )
10✔
3286

10✔
3287
                // As part of the returned error, we'll send our latest routing
10✔
3288
                // policy so the sending node obtains the most up to date data.
10✔
3289
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
20✔
3290
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
10✔
3291
                }
10✔
3292
                failure := l.createFailureWithUpdate(false, originalScid, cb)
10✔
3293
                return NewLinkError(failure)
10✔
3294
        }
3295

3296
        // Check whether the outgoing htlc satisfies the channel policy.
3297
        err := l.canSendHtlc(
47✔
3298
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
47✔
3299
                originalScid, customRecords,
47✔
3300
        )
47✔
3301
        if err != nil {
64✔
3302
                return err
17✔
3303
        }
17✔
3304

3305
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
3306
        // the following constraint: the incoming time-lock minus our time-lock
3307
        // delta should equal the outgoing time lock. Otherwise, whether the
3308
        // sender messed up, or an intermediate node tampered with the HTLC.
3309
        timeDelta := policy.TimeLockDelta
34✔
3310
        if incomingTimeout < outgoingTimeout+timeDelta {
36✔
3311
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
2✔
3312
                        "expected at least %v block delta, got %v block delta",
2✔
3313
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
2✔
3314

2✔
3315
                // Grab the latest routing policy so the sending node is up to
2✔
3316
                // date with our current policy.
2✔
3317
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
3318
                        return lnwire.NewIncorrectCltvExpiry(
2✔
3319
                                incomingTimeout, *upd,
2✔
3320
                        )
2✔
3321
                }
2✔
3322
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3323
                return NewLinkError(failure)
2✔
3324
        }
3325

3326
        return nil
32✔
3327
}
3328

3329
// CheckHtlcTransit should return a nil error if the passed HTLC details
3330
// satisfy the current channel policy.  Otherwise, a LinkError with a
3331
// valid protocol failure message should be returned in order to signal
3332
// the violation. This call is intended to be used for locally initiated
3333
// payments for which there is no corresponding incoming htlc.
3334
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
3335
        amt lnwire.MilliSatoshi, timeout uint32, heightNow uint32,
3336
        customRecords lnwire.CustomRecords) *LinkError {
410✔
3337

410✔
3338
        l.RLock()
410✔
3339
        policy := l.cfg.FwrdingPolicy
410✔
3340
        l.RUnlock()
410✔
3341

410✔
3342
        // We pass in hop.Source here as this is only used in the Switch when
410✔
3343
        // trying to send over a local link. This causes the fallback mechanism
410✔
3344
        // to occur.
410✔
3345
        return l.canSendHtlc(
410✔
3346
                policy, payHash, amt, timeout, heightNow, hop.Source,
410✔
3347
                customRecords,
410✔
3348
        )
410✔
3349
}
410✔
3350

3351
// canSendHtlc checks whether the given htlc parameters satisfy
3352
// the channel's amount and time lock constraints.
3353
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
3354
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
3355
        heightNow uint32, originalScid lnwire.ShortChannelID,
3356
        customRecords lnwire.CustomRecords) *LinkError {
453✔
3357

453✔
3358
        // As our first sanity check, we'll ensure that the passed HTLC isn't
453✔
3359
        // too small for the next hop. If so, then we'll cancel the HTLC
453✔
3360
        // directly.
453✔
3361
        if amt < policy.MinHTLCOut {
465✔
3362
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
12✔
3363
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
12✔
3364
                        amt)
12✔
3365

12✔
3366
                // As part of the returned error, we'll send our latest routing
12✔
3367
                // policy so the sending node obtains the most up to date data.
12✔
3368
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
24✔
3369
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
12✔
3370
                }
12✔
3371
                failure := l.createFailureWithUpdate(false, originalScid, cb)
12✔
3372
                return NewLinkError(failure)
12✔
3373
        }
3374

3375
        // Next, ensure that the passed HTLC isn't too large. If so, we'll
3376
        // cancel the HTLC directly.
3377
        if policy.MaxHTLC != 0 && amt > policy.MaxHTLC {
452✔
3378
                l.log.Warnf("outgoing htlc(%x) is too large: max_htlc=%v, "+
7✔
3379
                        "htlc_value=%v", payHash[:], policy.MaxHTLC, amt)
7✔
3380

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

3390
        // We want to avoid offering an HTLC which will expire in the near
3391
        // future, so we'll reject an HTLC if the outgoing expiration time is
3392
        // too close to the current height.
3393
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
444✔
3394
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
2✔
3395
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
2✔
3396
                        timeout, heightNow)
2✔
3397

2✔
3398
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
3399
                        return lnwire.NewExpiryTooSoon(*upd)
2✔
3400
                }
2✔
3401
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3402
                return NewLinkError(failure)
2✔
3403
        }
3404

3405
        // Check absolute max delta.
3406
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
441✔
3407
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
1✔
3408
                        "the future: got %v, but maximum is %v", payHash[:],
1✔
3409
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
1✔
3410

1✔
3411
                return NewLinkError(&lnwire.FailExpiryTooFar{})
1✔
3412
        }
1✔
3413

3414
        // We now check the available bandwidth to see if this HTLC can be
3415
        // forwarded.
3416
        availableBandwidth := l.Bandwidth()
439✔
3417
        auxBandwidth, err := fn.MapOptionZ(
439✔
3418
                l.cfg.AuxTrafficShaper,
439✔
3419
                func(ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
439✔
3420
                        var htlcBlob fn.Option[tlv.Blob]
×
3421
                        blob, err := customRecords.Serialize()
×
3422
                        if err != nil {
×
3423
                                return fn.Err[OptionalBandwidth](
×
3424
                                        fmt.Errorf("unable to serialize "+
×
3425
                                                "custom records: %w", err))
×
3426
                        }
×
3427

3428
                        if len(blob) > 0 {
×
3429
                                htlcBlob = fn.Some(blob)
×
3430
                        }
×
3431

3432
                        return l.AuxBandwidth(amt, originalScid, htlcBlob, ts)
×
3433
                },
3434
        ).Unpack()
3435
        if err != nil {
439✔
3436
                l.log.Errorf("Unable to determine aux bandwidth: %v", err)
×
3437
                return NewLinkError(&lnwire.FailTemporaryNodeFailure{})
×
3438
        }
×
3439

3440
        auxBandwidth.WhenSome(func(bandwidth lnwire.MilliSatoshi) {
439✔
3441
                availableBandwidth = bandwidth
×
3442
        })
×
3443

3444
        // Check to see if there is enough balance in this channel.
3445
        if amt > availableBandwidth {
444✔
3446
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
5✔
3447
                        "larger than %v", amt, l.Bandwidth())
5✔
3448
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
10✔
3449
                        return lnwire.NewTemporaryChannelFailure(upd)
5✔
3450
                }
5✔
3451
                failure := l.createFailureWithUpdate(false, originalScid, cb)
5✔
3452
                return NewDetailedLinkError(
5✔
3453
                        failure, OutgoingFailureInsufficientBalance,
5✔
3454
                )
5✔
3455
        }
3456

3457
        return nil
438✔
3458
}
3459

3460
// AuxBandwidth returns the bandwidth that can be used for a channel, expressed
3461
// in milli-satoshi. This might be different from the regular BTC bandwidth for
3462
// custom channels. This will always return fn.None() for a regular (non-custom)
3463
// channel.
3464
func (l *channelLink) AuxBandwidth(amount lnwire.MilliSatoshi,
3465
        cid lnwire.ShortChannelID, htlcBlob fn.Option[tlv.Blob],
3466
        ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
×
3467

×
3468
        unknownBandwidth := fn.None[lnwire.MilliSatoshi]()
×
3469

×
3470
        fundingBlob := l.FundingCustomBlob()
×
3471
        shouldHandle, err := ts.ShouldHandleTraffic(cid, fundingBlob)
×
3472
        if err != nil {
×
3473
                return fn.Err[OptionalBandwidth](fmt.Errorf("traffic shaper "+
×
3474
                        "failed to decide whether to handle traffic: %w", err))
×
3475
        }
×
3476

3477
        log.Debugf("ShortChannelID=%v: aux traffic shaper is handling "+
×
3478
                "traffic: %v", cid, shouldHandle)
×
3479

×
3480
        // If this channel isn't handled by the aux traffic shaper, we'll return
×
3481
        // early.
×
3482
        if !shouldHandle {
×
3483
                return fn.Ok(unknownBandwidth)
×
3484
        }
×
3485

3486
        // Ask for a specific bandwidth to be used for the channel.
3487
        commitmentBlob := l.CommitmentCustomBlob()
×
3488
        auxBandwidth, err := ts.PaymentBandwidth(
×
3489
                htlcBlob, commitmentBlob, l.Bandwidth(), amount,
×
3490
        )
×
3491
        if err != nil {
×
3492
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to get "+
×
3493
                        "bandwidth from external traffic shaper: %w", err))
×
3494
        }
×
3495

3496
        log.Debugf("ShortChannelID=%v: aux traffic shaper reported available "+
×
3497
                "bandwidth: %v", cid, auxBandwidth)
×
3498

×
3499
        return fn.Ok(fn.Some(auxBandwidth))
×
3500
}
3501

3502
// Stats returns the statistics of channel link.
3503
//
3504
// NOTE: Part of the ChannelLink interface.
3505
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
8✔
3506
        snapshot := l.channel.StateSnapshot()
8✔
3507

8✔
3508
        return snapshot.ChannelCommitment.CommitHeight,
8✔
3509
                snapshot.TotalMSatSent,
8✔
3510
                snapshot.TotalMSatReceived
8✔
3511
}
8✔
3512

3513
// String returns the string representation of channel link.
3514
//
3515
// NOTE: Part of the ChannelLink interface.
3516
func (l *channelLink) String() string {
×
3517
        return l.channel.ChannelPoint().String()
×
3518
}
×
3519

3520
// handleSwitchPacket handles the switch packets. This packets which might be
3521
// forwarded to us from another channel link in case the htlc update came from
3522
// another peer or if the update was created by user
3523
//
3524
// NOTE: Part of the packetHandler interface.
3525
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
483✔
3526
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
483✔
3527
                pkt.inKey(), pkt.outKey())
483✔
3528

483✔
3529
        return l.mailBox.AddPacket(pkt)
483✔
3530
}
483✔
3531

3532
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
3533
// to us from remote peer we have a channel with.
3534
//
3535
// NOTE: Part of the ChannelLink interface.
3536
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
3,383✔
3537
        select {
3,383✔
NEW
3538
        case <-l.cg.Done():
×
3539
                // Return early if the link is already in the process of
×
3540
                // quitting. It doesn't make sense to hand the message to the
×
3541
                // mailbox here.
×
3542
                return
×
3543
        default:
3,383✔
3544
        }
3545

3546
        err := l.mailBox.AddMessage(message)
3,383✔
3547
        if err != nil {
3,383✔
3548
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
3549
        }
×
3550
}
3551

3552
// updateChannelFee updates the commitment fee-per-kw on this channel by
3553
// committing to an update_fee message.
3554
func (l *channelLink) updateChannelFee(ctx context.Context,
3555
        feePerKw chainfee.SatPerKWeight) error {
3✔
3556

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

3✔
3559
        // We skip sending the UpdateFee message if the channel is not
3✔
3560
        // currently eligible to forward messages.
3✔
3561
        if !l.eligibleToUpdate() {
3✔
3562
                l.log.Debugf("skipping fee update for inactive channel")
×
3563
                return nil
×
3564
        }
×
3565

3566
        // Check and see if our proposed fee-rate would make us exceed the fee
3567
        // threshold.
3568
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
3✔
3569
        if err != nil {
3✔
3570
                // This shouldn't typically happen. If it does, it indicates
×
3571
                // something is wrong with our channel state.
×
3572
                return err
×
3573
        }
×
3574

3575
        if thresholdExceeded {
3✔
3576
                return fmt.Errorf("link fee threshold exceeded")
×
3577
        }
×
3578

3579
        // First, we'll update the local fee on our commitment.
3580
        if err := l.channel.UpdateFee(feePerKw); err != nil {
3✔
3581
                return err
×
3582
        }
×
3583

3584
        // The fee passed the channel's validation checks, so we update the
3585
        // mailbox feerate.
3586
        l.mailBox.SetFeeRate(feePerKw)
3✔
3587

3✔
3588
        // We'll then attempt to send a new UpdateFee message, and also lock it
3✔
3589
        // in immediately by triggering a commitment update.
3✔
3590
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
3✔
3591
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
3592
                return err
×
3593
        }
×
3594

3595
        return l.updateCommitTx(ctx)
3✔
3596
}
3597

3598
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
3599
// after receiving a revocation from the remote party, and reprocesses them in
3600
// the context of the provided forwarding package. Any settles or fails that
3601
// have already been acknowledged in the forwarding package will not be sent to
3602
// the switch.
3603
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
1,198✔
3604
        if len(fwdPkg.SettleFails) == 0 {
2,082✔
3605
                return
884✔
3606
        }
884✔
3607

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

318✔
3610
        var switchPackets []*htlcPacket
318✔
3611
        for i, update := range fwdPkg.SettleFails {
636✔
3612
                destRef := fwdPkg.DestRef(uint16(i))
318✔
3613

318✔
3614
                // Skip any settles or fails that have already been
318✔
3615
                // acknowledged by the incoming link that originated the
318✔
3616
                // forwarded Add.
318✔
3617
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
318✔
3618
                        continue
×
3619
                }
3620

3621
                // TODO(roasbeef): rework log entries to a shared
3622
                // interface.
3623

3624
                switch msg := update.UpdateMsg.(type) {
318✔
3625
                // A settle for an HTLC we previously forwarded HTLC has been
3626
                // received. So we'll forward the HTLC to the switch which will
3627
                // handle propagating the settle to the prior hop.
3628
                case *lnwire.UpdateFulfillHTLC:
195✔
3629
                        // If hodl.SettleIncoming is requested, we will not
195✔
3630
                        // forward the SETTLE to the switch and will not signal
195✔
3631
                        // a free slot on the commitment transaction.
195✔
3632
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
195✔
3633
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
3634
                                continue
×
3635
                        }
3636

3637
                        settlePacket := &htlcPacket{
195✔
3638
                                outgoingChanID: l.ShortChanID(),
195✔
3639
                                outgoingHTLCID: msg.ID,
195✔
3640
                                destRef:        &destRef,
195✔
3641
                                htlc:           msg,
195✔
3642
                        }
195✔
3643

195✔
3644
                        // Add the packet to the batch to be forwarded, and
195✔
3645
                        // notify the overflow queue that a spare spot has been
195✔
3646
                        // freed up within the commitment state.
195✔
3647
                        switchPackets = append(switchPackets, settlePacket)
195✔
3648

3649
                // A failureCode message for a previously forwarded HTLC has
3650
                // been received. As a result a new slot will be freed up in
3651
                // our commitment state, so we'll forward this to the switch so
3652
                // the backwards undo can continue.
3653
                case *lnwire.UpdateFailHTLC:
127✔
3654
                        // If hodl.SettleIncoming is requested, we will not
127✔
3655
                        // forward the FAIL to the switch and will not signal a
127✔
3656
                        // free slot on the commitment transaction.
127✔
3657
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
127✔
3658
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
3659
                                continue
×
3660
                        }
3661

3662
                        // Fetch the reason the HTLC was canceled so we can
3663
                        // continue to propagate it. This failure originated
3664
                        // from another node, so the linkFailure field is not
3665
                        // set on the packet.
3666
                        failPacket := &htlcPacket{
127✔
3667
                                outgoingChanID: l.ShortChanID(),
127✔
3668
                                outgoingHTLCID: msg.ID,
127✔
3669
                                destRef:        &destRef,
127✔
3670
                                htlc:           msg,
127✔
3671
                        }
127✔
3672

127✔
3673
                        l.log.Debugf("Failed to send HTLC with ID=%d", msg.ID)
127✔
3674

127✔
3675
                        // If the failure message lacks an HMAC (but includes
127✔
3676
                        // the 4 bytes for encoding the message and padding
127✔
3677
                        // lengths, then this means that we received it as an
127✔
3678
                        // UpdateFailMalformedHTLC. As a result, we'll signal
127✔
3679
                        // that we need to convert this error within the switch
127✔
3680
                        // to an actual error, by encrypting it as if we were
127✔
3681
                        // the originating hop.
127✔
3682
                        convertedErrorSize := lnwire.FailureMessageLength + 4
127✔
3683
                        if len(msg.Reason) == convertedErrorSize {
134✔
3684
                                failPacket.convertedError = true
7✔
3685
                        }
7✔
3686

3687
                        // Add the packet to the batch to be forwarded, and
3688
                        // notify the overflow queue that a spare spot has been
3689
                        // freed up within the commitment state.
3690
                        switchPackets = append(switchPackets, failPacket)
127✔
3691
                }
3692
        }
3693

3694
        // Only spawn the task forward packets we have a non-zero number.
3695
        if len(switchPackets) > 0 {
636✔
3696
                go l.forwardBatch(false, switchPackets...)
318✔
3697
        }
318✔
3698
}
3699

3700
// processRemoteAdds serially processes each of the Add payment descriptors
3701
// which have been "locked-in" by receiving a revocation from the remote party.
3702
// The forwarding package provided instructs how to process this batch,
3703
// indicating whether this is the first time these Adds are being processed, or
3704
// whether we are reprocessing as a result of a failure or restart. Adds that
3705
// have already been acknowledged in the forwarding package will be ignored.
3706
//
3707
//nolint:funlen
3708
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
1,200✔
3709
        l.log.Tracef("processing %d remote adds for height %d",
1,200✔
3710
                len(fwdPkg.Adds), fwdPkg.Height)
1,200✔
3711

1,200✔
3712
        decodeReqs := make(
1,200✔
3713
                []hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds),
1,200✔
3714
        )
1,200✔
3715
        for _, update := range fwdPkg.Adds {
1,653✔
3716
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
906✔
3717
                        // Before adding the new htlc to the state machine,
453✔
3718
                        // parse the onion object in order to obtain the
453✔
3719
                        // routing information with DecodeHopIterator function
453✔
3720
                        // which process the Sphinx packet.
453✔
3721
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
453✔
3722

453✔
3723
                        req := hop.DecodeHopIteratorRequest{
453✔
3724
                                OnionReader:    onionReader,
453✔
3725
                                RHash:          msg.PaymentHash[:],
453✔
3726
                                IncomingCltv:   msg.Expiry,
453✔
3727
                                IncomingAmount: msg.Amount,
453✔
3728
                                BlindingPoint:  msg.BlindingPoint,
453✔
3729
                        }
453✔
3730

453✔
3731
                        decodeReqs = append(decodeReqs, req)
453✔
3732
                }
453✔
3733
        }
3734

3735
        // Atomically decode the incoming htlcs, simultaneously checking for
3736
        // replay attempts. A particular index in the returned, spare list of
3737
        // channel iterators should only be used if the failure code at the
3738
        // same index is lnwire.FailCodeNone.
3739
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
1,200✔
3740
                fwdPkg.ID(), decodeReqs,
1,200✔
3741
        )
1,200✔
3742
        if sphinxErr != nil {
1,200✔
3743
                l.failf(LinkFailureError{code: ErrInternalError},
×
3744
                        "unable to decode hop iterators: %v", sphinxErr)
×
3745
                return
×
3746
        }
×
3747

3748
        var switchPackets []*htlcPacket
1,200✔
3749

1,200✔
3750
        for i, update := range fwdPkg.Adds {
1,653✔
3751
                idx := uint16(i)
453✔
3752

453✔
3753
                //nolint:forcetypeassert
453✔
3754
                add := *update.UpdateMsg.(*lnwire.UpdateAddHTLC)
453✔
3755
                sourceRef := fwdPkg.SourceRef(idx)
453✔
3756

453✔
3757
                if fwdPkg.State == channeldb.FwdStateProcessed &&
453✔
3758
                        fwdPkg.AckFilter.Contains(idx) {
453✔
3759

×
3760
                        // If this index is already found in the ack filter,
×
3761
                        // the response to this forwarding decision has already
×
3762
                        // been committed by one of our commitment txns. ADDs
×
3763
                        // in this state are waiting for the rest of the fwding
×
3764
                        // package to get acked before being garbage collected.
×
3765
                        continue
×
3766
                }
3767

3768
                // An incoming HTLC add has been full-locked in. As a result we
3769
                // can now examine the forwarding details of the HTLC, and the
3770
                // HTLC itself to decide if: we should forward it, cancel it,
3771
                // or are able to settle it (and it adheres to our fee related
3772
                // constraints).
3773

3774
                // Before adding the new htlc to the state machine, parse the
3775
                // onion object in order to obtain the routing information with
3776
                // DecodeHopIterator function which process the Sphinx packet.
3777
                chanIterator, failureCode := decodeResps[i].Result()
453✔
3778
                if failureCode != lnwire.CodeNone {
459✔
3779
                        // If we're unable to process the onion blob then we
6✔
3780
                        // should send the malformed htlc error to payment
6✔
3781
                        // sender.
6✔
3782
                        l.sendMalformedHTLCError(
6✔
3783
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
6✔
3784
                        )
6✔
3785

6✔
3786
                        l.log.Errorf("unable to decode onion hop "+
6✔
3787
                                "iterator: %v", failureCode)
6✔
3788
                        continue
6✔
3789
                }
3790

3791
                heightNow := l.cfg.BestHeight()
451✔
3792

451✔
3793
                pld, routeRole, pldErr := chanIterator.HopPayload()
451✔
3794
                if pldErr != nil {
455✔
3795
                        // If we're unable to process the onion payload, or we
4✔
3796
                        // received invalid onion payload failure, then we
4✔
3797
                        // should send an error back to the caller so the HTLC
4✔
3798
                        // can be canceled.
4✔
3799
                        var failedType uint64
4✔
3800

4✔
3801
                        // We need to get the underlying error value, so we
4✔
3802
                        // can't use errors.As as suggested by the linter.
4✔
3803
                        //nolint:errorlint
4✔
3804
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
4✔
3805
                                failedType = uint64(e.Type)
×
3806
                        }
×
3807

3808
                        // If we couldn't parse the payload, make our best
3809
                        // effort at creating an error encrypter that knows
3810
                        // what blinding type we were, but if we couldn't
3811
                        // parse the payload we have no way of knowing whether
3812
                        // we were the introduction node or not.
3813
                        //
3814
                        //nolint:ll
3815
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
4✔
3816
                                l.cfg.ExtractErrorEncrypter,
4✔
3817
                                // We need our route role here because we
4✔
3818
                                // couldn't parse or validate the payload.
4✔
3819
                                routeRole == hop.RouteRoleIntroduction,
4✔
3820
                        )
4✔
3821
                        if failCode != lnwire.CodeNone {
4✔
3822
                                l.log.Errorf("could not extract error "+
×
3823
                                        "encrypter: %v", pldErr)
×
3824

×
3825
                                // We can't process this htlc, send back
×
3826
                                // malformed.
×
3827
                                l.sendMalformedHTLCError(
×
3828
                                        add.ID, failureCode, add.OnionBlob,
×
3829
                                        &sourceRef,
×
3830
                                )
×
3831

×
3832
                                continue
×
3833
                        }
3834

3835
                        // TODO: currently none of the test unit infrastructure
3836
                        // is setup to handle TLV payloads, so testing this
3837
                        // would require implementing a separate mock iterator
3838
                        // for TLV payloads that also supports injecting invalid
3839
                        // payloads. Deferring this non-trival effort till a
3840
                        // later date
3841
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
4✔
3842

4✔
3843
                        l.sendHTLCError(
4✔
3844
                                add, sourceRef, NewLinkError(failure),
4✔
3845
                                obfuscator, false,
4✔
3846
                        )
4✔
3847

4✔
3848
                        l.log.Errorf("unable to decode forwarding "+
4✔
3849
                                "instructions: %v", pldErr)
4✔
3850

4✔
3851
                        continue
4✔
3852
                }
3853

3854
                // Retrieve onion obfuscator from onion blob in order to
3855
                // produce initial obfuscation of the onion failureCode.
3856
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
451✔
3857
                        l.cfg.ExtractErrorEncrypter,
451✔
3858
                        routeRole == hop.RouteRoleIntroduction,
451✔
3859
                )
451✔
3860
                if failureCode != lnwire.CodeNone {
452✔
3861
                        // If we're unable to process the onion blob than we
1✔
3862
                        // should send the malformed htlc error to payment
1✔
3863
                        // sender.
1✔
3864
                        l.sendMalformedHTLCError(
1✔
3865
                                add.ID, failureCode, add.OnionBlob,
1✔
3866
                                &sourceRef,
1✔
3867
                        )
1✔
3868

1✔
3869
                        l.log.Errorf("unable to decode onion "+
1✔
3870
                                "obfuscator: %v", failureCode)
1✔
3871

1✔
3872
                        continue
1✔
3873
                }
3874

3875
                fwdInfo := pld.ForwardingInfo()
450✔
3876

450✔
3877
                // Check whether the payload we've just processed uses our
450✔
3878
                // node as the introduction point (gave us a blinding key in
450✔
3879
                // the payload itself) and fail it back if we don't support
450✔
3880
                // route blinding.
450✔
3881
                if fwdInfo.NextBlinding.IsSome() &&
450✔
3882
                        l.cfg.DisallowRouteBlinding {
454✔
3883

4✔
3884
                        failure := lnwire.NewInvalidBlinding(
4✔
3885
                                fn.Some(add.OnionBlob),
4✔
3886
                        )
4✔
3887

4✔
3888
                        l.sendHTLCError(
4✔
3889
                                add, sourceRef, NewLinkError(failure),
4✔
3890
                                obfuscator, false,
4✔
3891
                        )
4✔
3892

4✔
3893
                        l.log.Error("rejected htlc that uses use as an " +
4✔
3894
                                "introduction point when we do not support " +
4✔
3895
                                "route blinding")
4✔
3896

4✔
3897
                        continue
4✔
3898
                }
3899

3900
                switch fwdInfo.NextHop {
450✔
3901
                case hop.Exit:
414✔
3902
                        err := l.processExitHop(
414✔
3903
                                add, sourceRef, obfuscator, fwdInfo,
414✔
3904
                                heightNow, pld,
414✔
3905
                        )
414✔
3906
                        if err != nil {
418✔
3907
                                l.failf(LinkFailureError{
4✔
3908
                                        code: ErrInternalError,
4✔
3909
                                }, err.Error()) //nolint
4✔
3910

4✔
3911
                                return
4✔
3912
                        }
4✔
3913

3914
                // There are additional channels left within this route. So
3915
                // we'll simply do some forwarding package book-keeping.
3916
                default:
40✔
3917
                        // If hodl.AddIncoming is requested, we will not
40✔
3918
                        // validate the forwarded ADD, nor will we send the
40✔
3919
                        // packet to the htlc switch.
40✔
3920
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
40✔
3921
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3922
                                continue
×
3923
                        }
3924

3925
                        endorseValue := l.experimentalEndorsement(
40✔
3926
                                record.CustomSet(add.CustomRecords),
40✔
3927
                        )
40✔
3928
                        endorseType := uint64(
40✔
3929
                                lnwire.ExperimentalEndorsementType,
40✔
3930
                        )
40✔
3931

40✔
3932
                        switch fwdPkg.State {
40✔
3933
                        case channeldb.FwdStateProcessed:
4✔
3934
                                // This add was not forwarded on the previous
4✔
3935
                                // processing phase, run it through our
4✔
3936
                                // validation pipeline to reproduce an error.
4✔
3937
                                // This may trigger a different error due to
4✔
3938
                                // expiring timelocks, but we expect that an
4✔
3939
                                // error will be reproduced.
4✔
3940
                                if !fwdPkg.FwdFilter.Contains(idx) {
4✔
3941
                                        break
×
3942
                                }
3943

3944
                                // Otherwise, it was already processed, we can
3945
                                // can collect it and continue.
3946
                                outgoingAdd := &lnwire.UpdateAddHTLC{
4✔
3947
                                        Expiry:        fwdInfo.OutgoingCTLV,
4✔
3948
                                        Amount:        fwdInfo.AmountToForward,
4✔
3949
                                        PaymentHash:   add.PaymentHash,
4✔
3950
                                        BlindingPoint: fwdInfo.NextBlinding,
4✔
3951
                                }
4✔
3952

4✔
3953
                                endorseValue.WhenSome(func(e byte) {
8✔
3954
                                        custRecords := map[uint64][]byte{
4✔
3955
                                                endorseType: {e},
4✔
3956
                                        }
4✔
3957

4✔
3958
                                        outgoingAdd.CustomRecords = custRecords
4✔
3959
                                })
4✔
3960

3961
                                // Finally, we'll encode the onion packet for
3962
                                // the _next_ hop using the hop iterator
3963
                                // decoded for the current hop.
3964
                                buf := bytes.NewBuffer(
4✔
3965
                                        outgoingAdd.OnionBlob[0:0],
4✔
3966
                                )
4✔
3967

4✔
3968
                                // We know this cannot fail, as this ADD
4✔
3969
                                // was marked forwarded in a previous
4✔
3970
                                // round of processing.
4✔
3971
                                chanIterator.EncodeNextHop(buf)
4✔
3972

4✔
3973
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
4✔
3974

4✔
3975
                                //nolint:ll
4✔
3976
                                updatePacket := &htlcPacket{
4✔
3977
                                        incomingChanID:       l.ShortChanID(),
4✔
3978
                                        incomingHTLCID:       add.ID,
4✔
3979
                                        outgoingChanID:       fwdInfo.NextHop,
4✔
3980
                                        sourceRef:            &sourceRef,
4✔
3981
                                        incomingAmount:       add.Amount,
4✔
3982
                                        amount:               outgoingAdd.Amount,
4✔
3983
                                        htlc:                 outgoingAdd,
4✔
3984
                                        obfuscator:           obfuscator,
4✔
3985
                                        incomingTimeout:      add.Expiry,
4✔
3986
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
4✔
3987
                                        inOnionCustomRecords: pld.CustomRecords(),
4✔
3988
                                        inboundFee:           inboundFee,
4✔
3989
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
4✔
3990
                                }
4✔
3991
                                switchPackets = append(
4✔
3992
                                        switchPackets, updatePacket,
4✔
3993
                                )
4✔
3994

4✔
3995
                                continue
4✔
3996
                        }
3997

3998
                        // TODO(roasbeef): ensure don't accept outrageous
3999
                        // timeout for htlc
4000

4001
                        // With all our forwarding constraints met, we'll
4002
                        // create the outgoing HTLC using the parameters as
4003
                        // specified in the forwarding info.
4004
                        addMsg := &lnwire.UpdateAddHTLC{
40✔
4005
                                Expiry:        fwdInfo.OutgoingCTLV,
40✔
4006
                                Amount:        fwdInfo.AmountToForward,
40✔
4007
                                PaymentHash:   add.PaymentHash,
40✔
4008
                                BlindingPoint: fwdInfo.NextBlinding,
40✔
4009
                        }
40✔
4010

40✔
4011
                        endorseValue.WhenSome(func(e byte) {
80✔
4012
                                addMsg.CustomRecords = map[uint64][]byte{
40✔
4013
                                        endorseType: {e},
40✔
4014
                                }
40✔
4015
                        })
40✔
4016

4017
                        // Finally, we'll encode the onion packet for the
4018
                        // _next_ hop using the hop iterator decoded for the
4019
                        // current hop.
4020
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
40✔
4021
                        err := chanIterator.EncodeNextHop(buf)
40✔
4022
                        if err != nil {
40✔
4023
                                l.log.Errorf("unable to encode the "+
×
4024
                                        "remaining route %v", err)
×
4025

×
4026
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
4027
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
4028
                                }
×
4029

4030
                                failure := l.createFailureWithUpdate(
×
4031
                                        true, hop.Source, cb,
×
4032
                                )
×
4033

×
4034
                                l.sendHTLCError(
×
4035
                                        add, sourceRef, NewLinkError(failure),
×
4036
                                        obfuscator, false,
×
4037
                                )
×
4038
                                continue
×
4039
                        }
4040

4041
                        // Now that this add has been reprocessed, only append
4042
                        // it to our list of packets to forward to the switch
4043
                        // this is the first time processing the add. If the
4044
                        // fwd pkg has already been processed, then we entered
4045
                        // the above section to recreate a previous error.  If
4046
                        // the packet had previously been forwarded, it would
4047
                        // have been added to switchPackets at the top of this
4048
                        // section.
4049
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
80✔
4050
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
40✔
4051

40✔
4052
                                //nolint:ll
40✔
4053
                                updatePacket := &htlcPacket{
40✔
4054
                                        incomingChanID:       l.ShortChanID(),
40✔
4055
                                        incomingHTLCID:       add.ID,
40✔
4056
                                        outgoingChanID:       fwdInfo.NextHop,
40✔
4057
                                        sourceRef:            &sourceRef,
40✔
4058
                                        incomingAmount:       add.Amount,
40✔
4059
                                        amount:               addMsg.Amount,
40✔
4060
                                        htlc:                 addMsg,
40✔
4061
                                        obfuscator:           obfuscator,
40✔
4062
                                        incomingTimeout:      add.Expiry,
40✔
4063
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
40✔
4064
                                        inOnionCustomRecords: pld.CustomRecords(),
40✔
4065
                                        inboundFee:           inboundFee,
40✔
4066
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
40✔
4067
                                }
40✔
4068

40✔
4069
                                fwdPkg.FwdFilter.Set(idx)
40✔
4070
                                switchPackets = append(switchPackets,
40✔
4071
                                        updatePacket)
40✔
4072
                        }
40✔
4073
                }
4074
        }
4075

4076
        // Commit the htlcs we are intending to forward if this package has not
4077
        // been fully processed.
4078
        if fwdPkg.State == channeldb.FwdStateLockedIn {
2,397✔
4079
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
1,197✔
4080
                if err != nil {
1,197✔
4081
                        l.failf(LinkFailureError{code: ErrInternalError},
×
4082
                                "unable to set fwd filter: %v", err)
×
4083
                        return
×
4084
                }
×
4085
        }
4086

4087
        if len(switchPackets) == 0 {
2,364✔
4088
                return
1,164✔
4089
        }
1,164✔
4090

4091
        replay := fwdPkg.State != channeldb.FwdStateLockedIn
40✔
4092

40✔
4093
        l.log.Debugf("forwarding %d packets to switch: replay=%v",
40✔
4094
                len(switchPackets), replay)
40✔
4095

40✔
4096
        // NOTE: This call is made synchronous so that we ensure all circuits
40✔
4097
        // are committed in the exact order that they are processed in the link.
40✔
4098
        // Failing to do this could cause reorderings/gaps in the range of
40✔
4099
        // opened circuits, which violates assumptions made by the circuit
40✔
4100
        // trimming.
40✔
4101
        l.forwardBatch(replay, switchPackets...)
40✔
4102
}
4103

4104
// experimentalEndorsement returns the value to set for our outgoing
4105
// experimental endorsement field, and a boolean indicating whether it should
4106
// be populated on the outgoing htlc.
4107
func (l *channelLink) experimentalEndorsement(
4108
        customUpdateAdd record.CustomSet) fn.Option[byte] {
40✔
4109

40✔
4110
        // Only relay experimental signal if we are within the experiment
40✔
4111
        // period.
40✔
4112
        if !l.cfg.ShouldFwdExpEndorsement() {
44✔
4113
                return fn.None[byte]()
4✔
4114
        }
4✔
4115

4116
        // If we don't have any custom records or the experimental field is
4117
        // not set, just forward a zero value.
4118
        if len(customUpdateAdd) == 0 {
80✔
4119
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
40✔
4120
        }
40✔
4121

4122
        t := uint64(lnwire.ExperimentalEndorsementType)
4✔
4123
        value, set := customUpdateAdd[t]
4✔
4124
        if !set {
4✔
4125
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4126
        }
×
4127

4128
        // We expect at least one byte for this field, consider it invalid if
4129
        // it has no data and just forward a zero value.
4130
        if len(value) == 0 {
4✔
4131
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4132
        }
×
4133

4134
        // Only forward endorsed if the incoming link is endorsed.
4135
        if value[0] == lnwire.ExperimentalEndorsed {
8✔
4136
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
4✔
4137
        }
4✔
4138

4139
        // Forward as unendorsed otherwise, including cases where we've
4140
        // received an invalid value that uses more than 3 bits of information.
4141
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
4✔
4142
}
4143

4144
// processExitHop handles an htlc for which this link is the exit hop. It
4145
// returns a boolean indicating whether the commitment tx needs an update.
4146
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
4147
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
4148
        fwdInfo hop.ForwardingInfo, heightNow uint32,
4149
        payload invoices.Payload) error {
414✔
4150

414✔
4151
        // If hodl.ExitSettle is requested, we will not validate the final hop's
414✔
4152
        // ADD, nor will we settle the corresponding invoice or respond with the
414✔
4153
        // preimage.
414✔
4154
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
525✔
4155
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
111✔
4156
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
111✔
4157

111✔
4158
                return nil
111✔
4159
        }
111✔
4160

4161
        // As we're the exit hop, we'll double check the hop-payload included in
4162
        // the HTLC to ensure that it was crafted correctly by the sender and
4163
        // is compatible with the HTLC we were extended.
4164
        //
4165
        // For a special case, if the fwdInfo doesn't have any blinded path
4166
        // information, and the incoming HTLC had special extra data, then
4167
        // we'll skip this amount check. The invoice acceptor will make sure we
4168
        // reject the HTLC if it's not containing the correct amount after
4169
        // examining the custom data.
4170
        hasBlindedPath := fwdInfo.NextBlinding.IsSome()
307✔
4171
        customHTLC := len(add.CustomRecords) > 0 && !hasBlindedPath
307✔
4172
        log.Tracef("Exit hop has_blinded_path=%v custom_htlc_bypass=%v",
307✔
4173
                hasBlindedPath, customHTLC)
307✔
4174

307✔
4175
        if !customHTLC && add.Amount < fwdInfo.AmountToForward {
407✔
4176
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
100✔
4177
                        "incompatible value: expected <=%v, got %v",
100✔
4178
                        add.PaymentHash, add.Amount, fwdInfo.AmountToForward)
100✔
4179

100✔
4180
                failure := NewLinkError(
100✔
4181
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
100✔
4182
                )
100✔
4183
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
100✔
4184

100✔
4185
                return nil
100✔
4186
        }
100✔
4187

4188
        // We'll also ensure that our time-lock value has been computed
4189
        // correctly.
4190
        if add.Expiry < fwdInfo.OutgoingCTLV {
208✔
4191
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
1✔
4192
                        "incompatible time-lock: expected <=%v, got %v",
1✔
4193
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
1✔
4194

1✔
4195
                failure := NewLinkError(
1✔
4196
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
1✔
4197
                )
1✔
4198

1✔
4199
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
1✔
4200

1✔
4201
                return nil
1✔
4202
        }
1✔
4203

4204
        // Notify the invoiceRegistry of the exit hop htlc. If we crash right
4205
        // after this, this code will be re-executed after restart. We will
4206
        // receive back a resolution event.
4207
        invoiceHash := lntypes.Hash(add.PaymentHash)
206✔
4208

206✔
4209
        circuitKey := models.CircuitKey{
206✔
4210
                ChanID: l.ShortChanID(),
206✔
4211
                HtlcID: add.ID,
206✔
4212
        }
206✔
4213

206✔
4214
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
206✔
4215
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
206✔
4216
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
206✔
4217
        )
206✔
4218
        if err != nil {
210✔
4219
                return err
4✔
4220
        }
4✔
4221

4222
        // Create a hodlHtlc struct and decide either resolved now or later.
4223
        htlc := hodlHtlc{
206✔
4224
                add:        add,
206✔
4225
                sourceRef:  sourceRef,
206✔
4226
                obfuscator: obfuscator,
206✔
4227
        }
206✔
4228

206✔
4229
        // If the event is nil, the invoice is being held, so we save payment
206✔
4230
        // descriptor for future reference.
206✔
4231
        if event == nil {
266✔
4232
                l.hodlMap[circuitKey] = htlc
60✔
4233
                return nil
60✔
4234
        }
60✔
4235

4236
        // Process the received resolution.
4237
        return l.processHtlcResolution(event, htlc)
150✔
4238
}
4239

4240
// settleHTLC settles the HTLC on the channel.
4241
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
4242
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
201✔
4243

201✔
4244
        hash := preimage.Hash()
201✔
4245

201✔
4246
        l.log.Infof("settling htlc %v as exit hop", hash)
201✔
4247

201✔
4248
        err := l.channel.SettleHTLC(
201✔
4249
                preimage, htlcIndex, &sourceRef, nil, nil,
201✔
4250
        )
201✔
4251
        if err != nil {
201✔
4252
                return fmt.Errorf("unable to settle htlc: %w", err)
×
4253
        }
×
4254

4255
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
4256
        // fake one before sending it to the peer.
4257
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
205✔
4258
                l.log.Warnf(hodl.BogusSettle.Warning())
4✔
4259
                preimage = [32]byte{}
4✔
4260
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
4✔
4261
        }
4✔
4262

4263
        // HTLC was successfully settled locally send notification about it
4264
        // remote peer.
4265
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
201✔
4266
                ChanID:          l.ChanID(),
201✔
4267
                ID:              htlcIndex,
201✔
4268
                PaymentPreimage: preimage,
201✔
4269
        })
201✔
4270

201✔
4271
        // Once we have successfully settled the htlc, notify a settle event.
201✔
4272
        l.cfg.HtlcNotifier.NotifySettleEvent(
201✔
4273
                HtlcKey{
201✔
4274
                        IncomingCircuit: models.CircuitKey{
201✔
4275
                                ChanID: l.ShortChanID(),
201✔
4276
                                HtlcID: htlcIndex,
201✔
4277
                        },
201✔
4278
                },
201✔
4279
                preimage,
201✔
4280
                HtlcEventTypeReceive,
201✔
4281
        )
201✔
4282

201✔
4283
        return nil
201✔
4284
}
4285

4286
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
4287
// err chan for the individual responses. This method is intended to be spawned
4288
// as a goroutine so the responses can be handled in the background.
4289
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
579✔
4290
        // Don't forward packets for which we already have a response in our
579✔
4291
        // mailbox. This could happen if a packet fails and is buffered in the
579✔
4292
        // mailbox, and the incoming link flaps.
579✔
4293
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
579✔
4294
        for _, pkt := range packets {
1,158✔
4295
                if l.mailBox.HasPacket(pkt.inKey()) {
583✔
4296
                        continue
4✔
4297
                }
4298

4299
                filteredPkts = append(filteredPkts, pkt)
579✔
4300
        }
4301

4302
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
579✔
4303
        if err != nil {
590✔
4304
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
4305
                        "settle/fail over htlcswitch: %v", err)
11✔
4306
        }
11✔
4307
}
4308

4309
// sendHTLCError functions cancels HTLC and send cancel message back to the
4310
// peer from which HTLC was received.
4311
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
4312
        sourceRef channeldb.AddRef, failure *LinkError,
4313
        e hop.ErrorEncrypter, isReceive bool) {
109✔
4314

109✔
4315
        reason, err := e.EncryptFirstHop(failure.WireMessage())
109✔
4316
        if err != nil {
109✔
4317
                l.log.Errorf("unable to obfuscate error: %v", err)
×
4318
                return
×
4319
        }
×
4320

4321
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
109✔
4322
        if err != nil {
109✔
4323
                l.log.Errorf("unable cancel htlc: %v", err)
×
4324
                return
×
4325
        }
×
4326

4327
        // Send the appropriate failure message depending on whether we're
4328
        // in a blinded route or not.
4329
        if err := l.sendIncomingHTLCFailureMsg(
109✔
4330
                add.ID, e, reason,
109✔
4331
        ); err != nil {
109✔
4332
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
4333
                return
×
4334
        }
×
4335

4336
        // Notify a link failure on our incoming link. Outgoing htlc information
4337
        // is not available at this point, because we have not decrypted the
4338
        // onion, so it is excluded.
4339
        var eventType HtlcEventType
109✔
4340
        if isReceive {
218✔
4341
                eventType = HtlcEventTypeReceive
109✔
4342
        } else {
113✔
4343
                eventType = HtlcEventTypeForward
4✔
4344
        }
4✔
4345

4346
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
109✔
4347
                HtlcKey{
109✔
4348
                        IncomingCircuit: models.CircuitKey{
109✔
4349
                                ChanID: l.ShortChanID(),
109✔
4350
                                HtlcID: add.ID,
109✔
4351
                        },
109✔
4352
                },
109✔
4353
                HtlcInfo{
109✔
4354
                        IncomingTimeLock: add.Expiry,
109✔
4355
                        IncomingAmt:      add.Amount,
109✔
4356
                },
109✔
4357
                eventType,
109✔
4358
                failure,
109✔
4359
                true,
109✔
4360
        )
109✔
4361
}
4362

4363
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
4364
// peer from which the HTLC was received. This function is primarily used to
4365
// handle the special requirements of route blinding, specifically:
4366
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
4367
// - Introduction nodes should return regular HTLC failure messages.
4368
//
4369
// It accepts the original opaque failure, which will be used in the case
4370
// that we're not part of a blinded route and an error encrypter that'll be
4371
// used if we are the introduction node and need to present an error as if
4372
// we're the failing party.
4373
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
4374
        e hop.ErrorEncrypter,
4375
        originalFailure lnwire.OpaqueReason) error {
125✔
4376

125✔
4377
        var msg lnwire.Message
125✔
4378
        switch {
125✔
4379
        // Our circuit's error encrypter will be nil if this was a locally
4380
        // initiated payment. We can only hit a blinded error for a locally
4381
        // initiated payment if we allow ourselves to be picked as the
4382
        // introduction node for our own payments and in that case we
4383
        // shouldn't reach this code. To prevent the HTLC getting stuck,
4384
        // we fail it back and log an error.
4385
        // code.
4386
        case e == nil:
×
4387
                msg = &lnwire.UpdateFailHTLC{
×
4388
                        ChanID: l.ChanID(),
×
4389
                        ID:     htlcIndex,
×
4390
                        Reason: originalFailure,
×
4391
                }
×
4392

×
4393
                l.log.Errorf("Unexpected blinded failure when "+
×
4394
                        "we are the sending node, incoming htlc: %v(%v)",
×
4395
                        l.ShortChanID(), htlcIndex)
×
4396

4397
        // For cleartext hops (ie, non-blinded/normal) we don't need any
4398
        // transformation on the error message and can just send the original.
4399
        case !e.Type().IsBlinded():
125✔
4400
                msg = &lnwire.UpdateFailHTLC{
125✔
4401
                        ChanID: l.ChanID(),
125✔
4402
                        ID:     htlcIndex,
125✔
4403
                        Reason: originalFailure,
125✔
4404
                }
125✔
4405

4406
        // When we're the introduction node, we need to convert the error to
4407
        // a UpdateFailHTLC.
4408
        case e.Type() == hop.EncrypterTypeIntroduction:
4✔
4409
                l.log.Debugf("Introduction blinded node switching out failure "+
4✔
4410
                        "error: %v", htlcIndex)
4✔
4411

4✔
4412
                // The specification does not require that we set the onion
4✔
4413
                // blob.
4✔
4414
                failureMsg := lnwire.NewInvalidBlinding(
4✔
4415
                        fn.None[[lnwire.OnionPacketSize]byte](),
4✔
4416
                )
4✔
4417
                reason, err := e.EncryptFirstHop(failureMsg)
4✔
4418
                if err != nil {
4✔
4419
                        return err
×
4420
                }
×
4421

4422
                msg = &lnwire.UpdateFailHTLC{
4✔
4423
                        ChanID: l.ChanID(),
4✔
4424
                        ID:     htlcIndex,
4✔
4425
                        Reason: reason,
4✔
4426
                }
4✔
4427

4428
        // If we are a relaying node, we need to switch out any error that
4429
        // we've received to a malformed HTLC error.
4430
        case e.Type() == hop.EncrypterTypeRelaying:
4✔
4431
                l.log.Debugf("Relaying blinded node switching out malformed "+
4✔
4432
                        "error: %v", htlcIndex)
4✔
4433

4✔
4434
                msg = &lnwire.UpdateFailMalformedHTLC{
4✔
4435
                        ChanID:      l.ChanID(),
4✔
4436
                        ID:          htlcIndex,
4✔
4437
                        FailureCode: lnwire.CodeInvalidBlinding,
4✔
4438
                }
4✔
4439

4440
        default:
×
4441
                return fmt.Errorf("unexpected encrypter: %d", e)
×
4442
        }
4443

4444
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
125✔
4445
                l.log.Warnf("Send update fail failed: %v", err)
×
4446
        }
×
4447

4448
        return nil
125✔
4449
}
4450

4451
// sendMalformedHTLCError helper function which sends the malformed HTLC update
4452
// to the payment sender.
4453
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
4454
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
4455
        sourceRef *channeldb.AddRef) {
7✔
4456

7✔
4457
        shaOnionBlob := sha256.Sum256(onionBlob[:])
7✔
4458
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
7✔
4459
        if err != nil {
7✔
4460
                l.log.Errorf("unable cancel htlc: %v", err)
×
4461
                return
×
4462
        }
×
4463

4464
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
7✔
4465
                ChanID:       l.ChanID(),
7✔
4466
                ID:           htlcIndex,
7✔
4467
                ShaOnionBlob: shaOnionBlob,
7✔
4468
                FailureCode:  code,
7✔
4469
        })
7✔
4470
}
4471

4472
// failf is a function which is used to encapsulate the action necessary for
4473
// properly failing the link. It takes a LinkFailureError, which will be passed
4474
// to the OnChannelFailure closure, in order for it to determine if we should
4475
// force close the channel, and if we should send an error message to the
4476
// remote peer.
4477
func (l *channelLink) failf(linkErr LinkFailureError, format string,
4478
        a ...interface{}) {
19✔
4479

19✔
4480
        reason := fmt.Errorf(format, a...)
19✔
4481

19✔
4482
        // Return if we have already notified about a failure.
19✔
4483
        if l.failed {
23✔
4484
                l.log.Warnf("ignoring link failure (%v), as link already "+
4✔
4485
                        "failed", reason)
4✔
4486
                return
4✔
4487
        }
4✔
4488

4489
        l.log.Errorf("failing link: %s with error: %v", reason, linkErr)
19✔
4490

19✔
4491
        // Set failed, such that we won't process any more updates, and notify
19✔
4492
        // the peer about the failure.
19✔
4493
        l.failed = true
19✔
4494
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
19✔
4495
}
4496

4497
// FundingCustomBlob returns the custom funding blob of the channel that this
4498
// link is associated with. The funding blob represents static information about
4499
// the channel that was created at channel funding time.
4500
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
4501
        if l.channel == nil {
×
4502
                return fn.None[tlv.Blob]()
×
4503
        }
×
4504

4505
        if l.channel.State() == nil {
×
4506
                return fn.None[tlv.Blob]()
×
4507
        }
×
4508

4509
        return l.channel.State().CustomBlob
×
4510
}
4511

4512
// CommitmentCustomBlob returns the custom blob of the current local commitment
4513
// of the channel that this link is associated with.
4514
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
4515
        if l.channel == nil {
×
4516
                return fn.None[tlv.Blob]()
×
4517
        }
×
4518

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