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

lightningnetwork / lnd / 16111275918

07 Jul 2025 07:59AM UTC coverage: 57.777% (-0.03%) from 57.803%
16111275918

Pull #10043

github

web-flow
Merge f70ed0693 into ff32e90d1
Pull Request #10043: multi: add context.Context param to more graphdb.V1Store methods

25 of 38 new or added lines in 8 files covered. (65.79%)

84 existing lines in 10 files now uncovered.

98445 of 170387 relevant lines covered (57.78%)

1.79 hits per line

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

66.94
/htlcswitch/link.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

118
        // ExtractErrorEncrypter function is responsible for decoding HTLC
119
        // Sphinx onion blob, and creating onion failure obfuscator.
120
        ExtractErrorEncrypter hop.ErrorEncrypterExtracter
121

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

130
        // Peer is a lightning network node with which we have the channel link
131
        // opened.
132
        Peer lnpeer.Peer
133

134
        // Registry is a sub-system which responsible for managing the invoices
135
        // in thread-safe manner.
136
        Registry InvoiceDatabase
137

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

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

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

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

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

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

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

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

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

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

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

202
        // BatchSize is the max size of a batch of updates done to the link
203
        // before we do a state update.
204
        BatchSize uint32
205

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

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

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

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

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

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

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

243
        // MaxAnchorsCommitFeeRate is the max commitment fee rate we'll use as
244
        // the initiator for channels of the anchor type.
245
        MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
246

247
        // NotifyActiveLink allows the link to tell the ChannelNotifier when a
248
        // link is first started.
249
        NotifyActiveLink func(wire.OutPoint)
250

251
        // NotifyActiveChannel allows the link to tell the ChannelNotifier when
252
        // channels becomes active.
253
        NotifyActiveChannel func(wire.OutPoint)
254

255
        // NotifyInactiveChannel allows the switch to tell the ChannelNotifier
256
        // when channels become inactive.
257
        NotifyInactiveChannel func(wire.OutPoint)
258

259
        // NotifyInactiveLinkEvent allows the switch to tell the
260
        // ChannelNotifier when a channel link become inactive.
261
        NotifyInactiveLinkEvent func(wire.OutPoint)
262

263
        // HtlcNotifier is an instance of a htlcNotifier which we will pipe htlc
264
        // events through.
265
        HtlcNotifier htlcNotifier
266

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

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

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

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

289
        // DisallowQuiescence is a flag that can be used to disable the
290
        // quiescence protocol.
291
        DisallowQuiescence bool
292

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

297
        // ShouldFwdExpEndorsement is a closure that indicates whether the link
298
        // should forward experimental endorsement signals.
299
        ShouldFwdExpEndorsement func() bool
300

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

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

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

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

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

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

340
        // channel is a lightning network channel to which we apply htlc
341
        // updates.
342
        channel *lnwallet.LightningChannel
343

344
        // cfg is a structure which carries all dependable fields/handlers
345
        // which may affect behaviour of the service.
346
        cfg ChannelLinkConfig
347

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

354
        // upstream is a channel that new messages sent from the remote peer to
355
        // the local peer will be sent across.
356
        upstream chan lnwire.Message
357

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

363
        // updateFeeTimer is the timer responsible for updating the link's
364
        // commitment fee every time it fires.
365
        updateFeeTimer *time.Timer
366

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

373
        sync.RWMutex
374

375
        // hodlQueue is used to receive exit hop htlc resolutions from invoice
376
        // registry.
377
        hodlQueue *queue.ConcurrentQueue
378

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

383
        // log is a link-specific logging instance.
384
        log btclog.Logger
385

386
        // isOutgoingAddBlocked tracks whether the channelLink can send an
387
        // UpdateAddHTLC.
388
        isOutgoingAddBlocked atomic.Bool
389

390
        // isIncomingAddBlocked tracks whether the channelLink can receive an
391
        // UpdateAddHTLC.
392
        isIncomingAddBlocked atomic.Bool
393

394
        // flushHooks is a hookMap that is triggered when we reach a channel
395
        // state with no live HTLCs.
396
        flushHooks hookMap
397

398
        // outgoingCommitHooks is a hookMap that is triggered after we send our
399
        // next CommitSig.
400
        outgoingCommitHooks hookMap
401

402
        // incomingCommitHooks is a hookMap that is triggered after we receive
403
        // our next CommitSig.
404
        incomingCommitHooks hookMap
405

406
        // quiescer is the state machine that tracks where this channel is with
407
        // respect to the quiescence protocol.
408
        quiescer Quiescer
409

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

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

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

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

433
        // newTransients is a channel that we use to accept new hooks into the
434
        // hookMap.
435
        newTransients chan func()
436
}
437

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

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

3✔
458
        return hookID
3✔
459
}
460

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

468
        m.transient = make(map[uint64]func())
3✔
469
}
470

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

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

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

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

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

509
        quiescenceReqs := make(
3✔
510
                chan fn.Req[fn.Unit, fn.Result[lntypes.ChannelParty]], 1,
3✔
511
        )
3✔
512

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

528
// A compile time check to ensure channelLink implements the ChannelLink
529
// interface.
530
var _ ChannelLink = (*channelLink)(nil)
531

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

543
        l.log.Info("starting")
3✔
544

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

556
        l.mailBox.ResetMessages()
3✔
557
        l.hodlQueue.Start()
3✔
558

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

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

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

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

601
        l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
3✔
602

3✔
603
        l.cg.WgAdd(1)
3✔
604
        go l.htlcManager(context.TODO())
3✔
605

3✔
606
        return nil
3✔
607
}
608

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

619
        l.log.Info("stopping")
3✔
620

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

3✔
625
        if l.cfg.ChainEvents.Cancel != nil {
6✔
626
                l.cfg.ChainEvents.Cancel()
3✔
627
        }
3✔
628

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

639
        if l.hodlQueue != nil {
6✔
640
                l.hodlQueue.Stop()
3✔
641
        }
3✔
642

643
        l.cg.Quit()
3✔
644
        l.cg.WgWait()
3✔
645

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

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

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

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

3✔
682
        return l.eligibleToForward()
3✔
683
}
3✔
684

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

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

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

717
        return l.isIncomingAddBlocked.Swap(false)
×
718
}
719

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

728
        return !l.isIncomingAddBlocked.Swap(true)
3✔
729
}
730

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

738
        return l.isIncomingAddBlocked.Load()
3✔
739
}
740

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

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

3✔
758
        if direction == Outgoing {
6✔
759
                queue = l.outgoingCommitHooks.newTransients
3✔
760
        } else {
3✔
761
                queue = l.incomingCommitHooks.newTransients
×
762
        }
×
763

764
        select {
3✔
765
        case queue <- hook:
3✔
766
        case <-l.cg.Done():
×
767
        }
768
}
769

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

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

788
        return out
3✔
789
}
790

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

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

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

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

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

×
825
        return feePerKw, nil
×
826
}
827

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

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

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

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

852
        // Otherwise, we won't modify our fee.
853
        default:
×
854
                return false
×
855
        }
856
}
857

858
// failCb is used to cut down on the argument verbosity.
859
type failCb func(update *lnwire.ChannelUpdate1) lnwire.FailureMessage
860

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

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

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

887
        return cb(update)
3✔
888
}
889

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

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

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

912
        var msgsToReSend []lnwire.Message
3✔
913

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

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

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

3✔
937
                        l.log.Infof("resending ChannelReady message to peer")
3✔
938

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

945
                        channelReadyMsg := lnwire.NewChannelReady(
3✔
946
                                l.ChanID(), nextRevocation,
3✔
947
                        )
3✔
948

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

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

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

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

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

3✔
988
                var (
3✔
989
                        openedCircuits []CircuitKey
3✔
990
                        closedCircuits []CircuitKey
3✔
991
                )
3✔
992

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

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

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

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

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

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

1032
        return nil
3✔
1033
}
1034

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

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

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

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

1060
        return nil
3✔
1061
}
1062

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

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

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

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

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

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

1108
        return nil
3✔
1109
}
1110

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

3✔
1120
        l.cfg.FwdPkgGCTicker.Resume()
3✔
1121
        defer l.cfg.FwdPkgGCTicker.Stop()
3✔
1122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1434
                        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
×
1435

×
1436
                        newCommitFee := l.channel.IdealCommitFeeRate(
×
1437
                                netFee, minRelayFee,
×
1438
                                l.cfg.MaxAnchorsCommitFeeRate,
×
1439
                                l.cfg.MaxFeeAllocation,
×
1440
                        )
×
1441

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

×
1451
                                continue
×
1452
                        }
1453

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

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

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

1478
                        return
3✔
1479

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

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

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

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

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

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

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

1539
                case qReq := <-l.quiescenceReqs:
3✔
1540
                        l.quiescer.InitStfu(qReq)
3✔
1541

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

1553
                case <-l.cg.Done():
3✔
1554
                        return
3✔
1555
                }
1556
        }
1557
}
1558

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

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

1578
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
3✔
1579
                        return err
×
1580
                }
×
1581

1582
                // Clean up hodl map.
1583
                delete(l.hodlMap, circuitKey)
3✔
1584

3✔
1585
                select {
3✔
1586
                case item := <-l.hodlQueue.ChanOut():
3✔
1587
                        htlcResolution = item.(invoices.HtlcResolution)
3✔
1588

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

1593
                default:
3✔
1594
                        break loop
3✔
1595
                }
1596
        }
1597

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

1603
        return nil
3✔
1604
}
1605

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

3✔
1612
        circuitKey := resolution.CircuitKey()
3✔
1613

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

3✔
1623
                return l.settleHTLC(
3✔
1624
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
3✔
1625
                )
3✔
1626

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

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

3✔
1637
                l.sendHTLCError(
3✔
1638
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
3✔
1639
                        true,
3✔
1640
                )
3✔
1641
                return nil
3✔
1642

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

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

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

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

3✔
1672
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
3✔
1673
}
1674

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

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

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

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

×
1700
                return NewDetailedLinkError(
×
1701
                        &lnwire.FailTemporaryChannelFailure{},
×
1702
                        OutgoingFailureLinkNotEligible,
×
1703
                )
×
1704
        }
×
1705

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

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

×
1721
                l.mailBox.FailAdd(pkt)
×
1722

×
1723
                return NewDetailedLinkError(
×
1724
                        lnwire.NewTemporaryChannelFailure(nil),
×
1725
                        OutgoingFailureDownstreamHtlcAdd,
×
1726
                )
×
1727
        }
×
1728

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

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

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

3✔
1757
                return NewDetailedLinkError(
3✔
1758
                        lnwire.NewTemporaryChannelFailure(nil),
3✔
1759
                        OutgoingFailureDownstreamHtlcAdd,
3✔
1760
                )
3✔
1761
        }
3✔
1762

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

3✔
1768
        pkt.outgoingChanID = l.ShortChanID()
3✔
1769
        pkt.outgoingHTLCID = index
3✔
1770
        htlc.ID = index
3✔
1771

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

3✔
1775
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
3✔
1776
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
3✔
1777

3✔
1778
        _ = l.cfg.Peer.SendMessage(false, htlc)
3✔
1779

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

3✔
1792
        l.tryBatchUpdateCommitTx(ctx)
3✔
1793

3✔
1794
        return nil
3✔
1795
}
1796

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

3✔
1806
        if pkt.htlc.MsgType().IsChannelUpdate() &&
3✔
1807
                !l.quiescer.CanSendUpdates() {
3✔
1808

×
1809
                l.log.Warnf("unable to process channel update. "+
×
1810
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1811

×
1812
                return
×
1813
        }
×
1814

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

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

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

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

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

×
1860
                        return
×
1861
                }
1862

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

3✔
1866
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
3✔
1867

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

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

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

3✔
1885
                // Immediately update the commitment tx to minimize latency.
3✔
1886
                l.updateCommitTxOrFail(ctx)
3✔
1887

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

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

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

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

3✔
1926
                        return
3✔
1927
                }
1928

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

3✔
1932
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
3✔
1933

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

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

×
1954
                        return
×
1955
                }
×
1956

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

1975
                // Immediately update the commitment tx to minimize latency.
1976
                l.updateCommitTxOrFail(ctx)
3✔
1977
        }
1978
}
1979

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

1988
        l.updateCommitTxOrFail(ctx)
3✔
1989
}
1990

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

×
1998
        l.log.Debugf("cleaning up spurious response for incoming "+
×
1999
                "circuit-key=%v", inKey)
×
2000

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

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

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

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

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

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

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

3✔
2063
        l.log.Tracef("receive upstream msg %v, handling now... ", msg.MsgType())
3✔
2064
        defer l.log.Tracef("handled upstream msg %v", msg.MsgType())
3✔
2065

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

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

×
2105
                        return
×
2106
                }
×
2107

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

×
2118
                        return
×
2119
                }
×
2120

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

×
2130
                        return
×
2131
                }
×
2132

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

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

2146
        case *lnwire.UpdateFulfillHTLC:
3✔
2147
                pre := msg.PaymentPreimage
3✔
2148
                idx := msg.ID
3✔
2149

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

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

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

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

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

3✔
2196
                // Pipeline this settle, send it to the switch.
3✔
2197
                go l.forwardBatch(false, settlePacket)
3✔
2198

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

2213
                case lnwire.CodeInvalidOnionKey:
×
2214
                        failure = &lnwire.FailInvalidOnionKey{
×
2215
                                OnionSHA256: msg.ShaOnionBlob,
×
2216
                        }
×
2217

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

2230
                default:
×
2231
                        l.log.Warnf("unexpected failure code received in "+
×
2232
                                "UpdateFailMailformedHTLC: %v", msg.FailureCode)
×
2233

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

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

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

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

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

×
2291
                                return
×
2292
                        }
×
2293
                }
2294

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

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

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

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

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

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

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

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

3✔
2412
                l.cfg.Peer.SendMessage(false, nextRevocation)
3✔
2413

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

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

2443
                select {
3✔
2444
                case <-l.cg.Done():
×
2445
                        return
×
2446
                default:
3✔
2447
                }
2448

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

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

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

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

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

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

2513
                select {
3✔
2514
                case <-l.cg.Done():
×
2515
                        return
×
2516
                default:
3✔
2517
                }
2518

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

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

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

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

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

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

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

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

×
2595
                        return
×
2596
                }
×
2597

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

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

2614
                // Update the mailbox's feerate as well.
2615
                l.mailBox.SetFeeRate(fee)
×
2616

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

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

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

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

2653
}
2654

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

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

2671
        return nil
×
2672
}
2673

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

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

3✔
2696
        return pendingOnLocal == 0 && pendingOnRemote == 0
3✔
2697
}
3✔
2698

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

2718
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
3✔
2719
                l.mailBox.AckPacket(inKey)
3✔
2720
        }
2721

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

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

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

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

3✔
2753
        return nil
3✔
2754
}
2755

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

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

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

2779
        return true
3✔
2780
}
2781

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

2796
        // Reset the batch, but keep the backing buffer to avoid reallocating.
2797
        l.keystoneBatch = l.keystoneBatch[:0]
3✔
2798

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

2808
        ctx, done := l.cg.Create(ctx)
3✔
2809
        defer done()
3✔
2810

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

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

3✔
2822
                return nil
3✔
2823
        } else if err != nil {
6✔
2824
                return err
×
2825
        }
×
2826

2827
        if err := l.ackDownStreamPackets(); err != nil {
3✔
2828
                return err
×
2829
        }
×
2830

2831
        l.cfg.PendingCommitTicker.Pause()
3✔
2832
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
3✔
2833

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

2847
        select {
3✔
2848
        case <-l.cg.Done():
×
2849
                return ErrLinkShuttingDown
×
2850
        default:
3✔
2851
        }
2852

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

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

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

3✔
2873
        return nil
3✔
2874
}
2875

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

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

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

3✔
2899
        return l.channel.ShortChanID()
3✔
2900
}
3✔
2901

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

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

2921
        return hop.Source, nil
3✔
2922
}
2923

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

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

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

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

3✔
2960
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
3✔
2961
}
3✔
2962

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

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

3✔
2980
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
3✔
2981
}
3✔
2982

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

2993
        return l.channel.State().LocalCommitment.CommitFee
3✔
2994
}
2995

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

×
3010
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
×
3011

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

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

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

×
3032
                return true, nil
×
3033
        }
×
3034

3035
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
×
3036
                remoteFee,
×
3037
        )
×
3038

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

×
3044
                return true, nil
×
3045
        }
×
3046

3047
        return false, nil
×
3048
}
3049

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

3✔
3061
        dustClosure := l.getDustClosure()
3✔
3062

3✔
3063
        feeRate := l.channel.WorstCaseFeeRate()
3✔
3064

3✔
3065
        amount := htlc.Amount.ToSatoshis()
3✔
3066

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

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

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

3✔
3082
        if l.getCommitFee(true) > commitFee {
3✔
UNCOV
3083
                commitFee = l.getCommitFee(true)
×
UNCOV
3084
        }
×
3085

3086
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
3✔
3087

3✔
3088
        localDustSum += commitFeeMSat
3✔
3089
        remoteDustSum += commitFeeMSat
3✔
3090

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

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

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

×
3113
                return true
×
3114
        }
×
3115

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

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

×
3132
                return true
×
3133
        }
×
3134

3135
        return false
3✔
3136
}
3137

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

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

3✔
3150
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
3✔
3151
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
6✔
3152

3✔
3153
                var dustLimit btcutil.Amount
3✔
3154
                if whoseCommit.IsLocal() {
6✔
3155
                        dustLimit = localDustLimit
3✔
3156
                } else {
6✔
3157
                        dustLimit = remoteDustLimit
3✔
3158
                }
3✔
3159

3160
                return lnwallet.HtlcIsDust(
3✔
3161
                        chantype, incoming, whoseCommit, feerate, amt,
3✔
3162
                        dustLimit,
3✔
3163
                )
3✔
3164
        }
3165

3166
        return isDust
3✔
3167
}
3168

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

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

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

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

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

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

3✔
3216
        l.Lock()
3✔
3217
        l.cfg.FailAliasUpdate = closure
3✔
3218
        l.Unlock()
3✔
3219
}
3✔
3220

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

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

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

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

3✔
3250
        l.Lock()
3✔
3251
        defer l.Unlock()
3✔
3252

3✔
3253
        l.cfg.FwrdingPolicy = newPolicy
3✔
3254
}
3✔
3255

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

3✔
3269
        l.RLock()
3✔
3270
        policy := l.cfg.FwrdingPolicy
3✔
3271
        l.RUnlock()
3✔
3272

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

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

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

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

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

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

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

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

3343
        return nil
3✔
3344
}
3345

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

3✔
3355
        l.RLock()
3✔
3356
        policy := l.cfg.FwrdingPolicy
3✔
3357
        l.RUnlock()
3✔
3358

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

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

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

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

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

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

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

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

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

×
3428
                return NewLinkError(&lnwire.FailExpiryTooFar{})
×
3429
        }
×
3430

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

3445
                        if len(blob) > 0 {
×
3446
                                htlcBlob = fn.Some(blob)
×
3447
                        }
×
3448

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

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

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

3478
        return nil
3✔
3479
}
3480

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

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

3496
        log.Debugf("ShortChannelID=%v: aux traffic shaper is handling "+
×
3497
                "traffic: %v", cid, shouldHandle)
×
3498

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

3507
        peerBytes := l.cfg.Peer.PubKey()
×
3508

×
3509
        peer, err := route.NewVertexFromBytes(peerBytes[:])
×
3510
        if err != nil {
×
3511
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to decode "+
×
3512
                        "peer pub key: %v", err))
×
3513
        }
×
3514

3515
        // Ask for a specific bandwidth to be used for the channel.
3516
        commitmentBlob := l.CommitmentCustomBlob()
×
3517
        auxBandwidth, err := ts.PaymentBandwidth(
×
3518
                fundingBlob, htlcBlob, commitmentBlob, l.Bandwidth(), amount,
×
3519
                l.channel.FetchLatestAuxHTLCView(), peer,
×
3520
        )
×
3521
        if err != nil {
×
3522
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to get "+
×
3523
                        "bandwidth from external traffic shaper: %w", err))
×
3524
        }
×
3525

3526
        log.Debugf("ShortChannelID=%v: aux traffic shaper reported available "+
×
3527
                "bandwidth: %v", cid, auxBandwidth)
×
3528

×
3529
        return fn.Ok(OptionalBandwidth{
×
3530
                IsHandled: true,
×
3531
                Bandwidth: fn.Some(auxBandwidth),
×
3532
        })
×
3533
}
3534

3535
// Stats returns the statistics of channel link.
3536
//
3537
// NOTE: Part of the ChannelLink interface.
3538
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
3✔
3539
        snapshot := l.channel.StateSnapshot()
3✔
3540

3✔
3541
        return snapshot.ChannelCommitment.CommitHeight,
3✔
3542
                snapshot.TotalMSatSent,
3✔
3543
                snapshot.TotalMSatReceived
3✔
3544
}
3✔
3545

3546
// String returns the string representation of channel link.
3547
//
3548
// NOTE: Part of the ChannelLink interface.
3549
func (l *channelLink) String() string {
×
3550
        return l.channel.ChannelPoint().String()
×
3551
}
×
3552

3553
// handleSwitchPacket handles the switch packets. This packets which might be
3554
// forwarded to us from another channel link in case the htlc update came from
3555
// another peer or if the update was created by user
3556
//
3557
// NOTE: Part of the packetHandler interface.
3558
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
3✔
3559
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
3✔
3560
                pkt.inKey(), pkt.outKey())
3✔
3561

3✔
3562
        return l.mailBox.AddPacket(pkt)
3✔
3563
}
3✔
3564

3565
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
3566
// to us from remote peer we have a channel with.
3567
//
3568
// NOTE: Part of the ChannelLink interface.
3569
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
3✔
3570
        select {
3✔
3571
        case <-l.cg.Done():
×
3572
                // Return early if the link is already in the process of
×
3573
                // quitting. It doesn't make sense to hand the message to the
×
3574
                // mailbox here.
×
3575
                return
×
3576
        default:
3✔
3577
        }
3578

3579
        err := l.mailBox.AddMessage(message)
3✔
3580
        if err != nil {
3✔
3581
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
3582
        }
×
3583
}
3584

3585
// updateChannelFee updates the commitment fee-per-kw on this channel by
3586
// committing to an update_fee message.
3587
func (l *channelLink) updateChannelFee(ctx context.Context,
3588
        feePerKw chainfee.SatPerKWeight) error {
×
3589

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

×
3592
        // We skip sending the UpdateFee message if the channel is not
×
3593
        // currently eligible to forward messages.
×
3594
        if !l.eligibleToUpdate() {
×
3595
                l.log.Debugf("skipping fee update for inactive channel")
×
3596
                return nil
×
3597
        }
×
3598

3599
        // Check and see if our proposed fee-rate would make us exceed the fee
3600
        // threshold.
3601
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
×
3602
        if err != nil {
×
3603
                // This shouldn't typically happen. If it does, it indicates
×
3604
                // something is wrong with our channel state.
×
3605
                return err
×
3606
        }
×
3607

3608
        if thresholdExceeded {
×
3609
                return fmt.Errorf("link fee threshold exceeded")
×
3610
        }
×
3611

3612
        // First, we'll update the local fee on our commitment.
3613
        if err := l.channel.UpdateFee(feePerKw); err != nil {
×
3614
                return err
×
3615
        }
×
3616

3617
        // The fee passed the channel's validation checks, so we update the
3618
        // mailbox feerate.
3619
        l.mailBox.SetFeeRate(feePerKw)
×
3620

×
3621
        // We'll then attempt to send a new UpdateFee message, and also lock it
×
3622
        // in immediately by triggering a commitment update.
×
3623
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
×
3624
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
×
3625
                return err
×
3626
        }
×
3627

3628
        return l.updateCommitTx(ctx)
×
3629
}
3630

3631
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
3632
// after receiving a revocation from the remote party, and reprocesses them in
3633
// the context of the provided forwarding package. Any settles or fails that
3634
// have already been acknowledged in the forwarding package will not be sent to
3635
// the switch.
3636
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
3✔
3637
        if len(fwdPkg.SettleFails) == 0 {
6✔
3638
                l.log.Trace("fwd package has no settle/fails to process " +
3✔
3639
                        "exiting early")
3✔
3640

3✔
3641
                return
3✔
3642
        }
3✔
3643

3644
        // Exit early if the fwdPkg is already processed.
3645
        if fwdPkg.State == channeldb.FwdStateCompleted {
3✔
3646
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
3647

×
3648
                return
×
3649
        }
×
3650

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

3✔
3653
        var switchPackets []*htlcPacket
3✔
3654
        for i, update := range fwdPkg.SettleFails {
6✔
3655
                destRef := fwdPkg.DestRef(uint16(i))
3✔
3656

3✔
3657
                // Skip any settles or fails that have already been
3✔
3658
                // acknowledged by the incoming link that originated the
3✔
3659
                // forwarded Add.
3✔
3660
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
3✔
3661
                        continue
×
3662
                }
3663

3664
                // TODO(roasbeef): rework log entries to a shared
3665
                // interface.
3666

3667
                switch msg := update.UpdateMsg.(type) {
3✔
3668
                // A settle for an HTLC we previously forwarded HTLC has been
3669
                // received. So we'll forward the HTLC to the switch which will
3670
                // handle propagating the settle to the prior hop.
3671
                case *lnwire.UpdateFulfillHTLC:
3✔
3672
                        // If hodl.SettleIncoming is requested, we will not
3✔
3673
                        // forward the SETTLE to the switch and will not signal
3✔
3674
                        // a free slot on the commitment transaction.
3✔
3675
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
3✔
3676
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
3677
                                continue
×
3678
                        }
3679

3680
                        settlePacket := &htlcPacket{
3✔
3681
                                outgoingChanID: l.ShortChanID(),
3✔
3682
                                outgoingHTLCID: msg.ID,
3✔
3683
                                destRef:        &destRef,
3✔
3684
                                htlc:           msg,
3✔
3685
                        }
3✔
3686

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

3692
                // A failureCode message for a previously forwarded HTLC has
3693
                // been received. As a result a new slot will be freed up in
3694
                // our commitment state, so we'll forward this to the switch so
3695
                // the backwards undo can continue.
3696
                case *lnwire.UpdateFailHTLC:
3✔
3697
                        // If hodl.SettleIncoming is requested, we will not
3✔
3698
                        // forward the FAIL to the switch and will not signal a
3✔
3699
                        // free slot on the commitment transaction.
3✔
3700
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
3✔
3701
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
3702
                                continue
×
3703
                        }
3704

3705
                        // Fetch the reason the HTLC was canceled so we can
3706
                        // continue to propagate it. This failure originated
3707
                        // from another node, so the linkFailure field is not
3708
                        // set on the packet.
3709
                        failPacket := &htlcPacket{
3✔
3710
                                outgoingChanID: l.ShortChanID(),
3✔
3711
                                outgoingHTLCID: msg.ID,
3✔
3712
                                destRef:        &destRef,
3✔
3713
                                htlc:           msg,
3✔
3714
                        }
3✔
3715

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

3✔
3718
                        // If the failure message lacks an HMAC (but includes
3✔
3719
                        // the 4 bytes for encoding the message and padding
3✔
3720
                        // lengths, then this means that we received it as an
3✔
3721
                        // UpdateFailMalformedHTLC. As a result, we'll signal
3✔
3722
                        // that we need to convert this error within the switch
3✔
3723
                        // to an actual error, by encrypting it as if we were
3✔
3724
                        // the originating hop.
3✔
3725
                        convertedErrorSize := lnwire.FailureMessageLength + 4
3✔
3726
                        if len(msg.Reason) == convertedErrorSize {
6✔
3727
                                failPacket.convertedError = true
3✔
3728
                        }
3✔
3729

3730
                        // Add the packet to the batch to be forwarded, and
3731
                        // notify the overflow queue that a spare spot has been
3732
                        // freed up within the commitment state.
3733
                        switchPackets = append(switchPackets, failPacket)
3✔
3734
                }
3735
        }
3736

3737
        // Only spawn the task forward packets we have a non-zero number.
3738
        if len(switchPackets) > 0 {
6✔
3739
                go l.forwardBatch(false, switchPackets...)
3✔
3740
        }
3✔
3741
}
3742

3743
// processRemoteAdds serially processes each of the Add payment descriptors
3744
// which have been "locked-in" by receiving a revocation from the remote party.
3745
// The forwarding package provided instructs how to process this batch,
3746
// indicating whether this is the first time these Adds are being processed, or
3747
// whether we are reprocessing as a result of a failure or restart. Adds that
3748
// have already been acknowledged in the forwarding package will be ignored.
3749
//
3750
//nolint:funlen
3751
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
3✔
3752
        // Exit early if there are no adds to process.
3✔
3753
        if len(fwdPkg.Adds) == 0 {
6✔
3754
                l.log.Trace("fwd package has no adds to process exiting early")
3✔
3755

3✔
3756
                return
3✔
3757
        }
3✔
3758

3759
        // Exit early if the fwdPkg is already processed.
3760
        if fwdPkg.State == channeldb.FwdStateCompleted {
3✔
3761
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
3762

×
3763
                return
×
3764
        }
×
3765

3766
        l.log.Tracef("processing %d remote adds for height %d",
3✔
3767
                len(fwdPkg.Adds), fwdPkg.Height)
3✔
3768

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

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

3✔
3777
        for i, update := range fwdPkg.Adds {
6✔
3778
                // If this index is already found in the ack filter, the
3✔
3779
                // response to this forwarding decision has already been
3✔
3780
                // committed by one of our commitment txns. ADDs in this state
3✔
3781
                // are waiting for the rest of the fwding package to get acked
3✔
3782
                // before being garbage collected.
3✔
3783
                if fwdPkg.State == channeldb.FwdStateProcessed &&
3✔
3784
                        fwdPkg.AckFilter.Contains(uint16(i)) {
3✔
3785

×
3786
                        continue
×
3787
                }
3788

3789
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
6✔
3790
                        // Before adding the new htlc to the state machine,
3✔
3791
                        // parse the onion object in order to obtain the
3✔
3792
                        // routing information with DecodeHopIterator function
3✔
3793
                        // which process the Sphinx packet.
3✔
3794
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
3✔
3795

3✔
3796
                        req := hop.DecodeHopIteratorRequest{
3✔
3797
                                OnionReader:    onionReader,
3✔
3798
                                RHash:          msg.PaymentHash[:],
3✔
3799
                                IncomingCltv:   msg.Expiry,
3✔
3800
                                IncomingAmount: msg.Amount,
3✔
3801
                                BlindingPoint:  msg.BlindingPoint,
3✔
3802
                        }
3✔
3803

3✔
3804
                        decodeReqs = append(decodeReqs, req)
3✔
3805
                        unackedAdds = append(unackedAdds, msg)
3✔
3806
                }
3✔
3807
        }
3808

3809
        // If the fwdPkg has already been processed, it means we are
3810
        // reforwarding the packets again, which happens only on a restart.
3811
        reforward := fwdPkg.State == channeldb.FwdStateProcessed
3✔
3812

3✔
3813
        // Atomically decode the incoming htlcs, simultaneously checking for
3✔
3814
        // replay attempts. A particular index in the returned, spare list of
3✔
3815
        // channel iterators should only be used if the failure code at the
3✔
3816
        // same index is lnwire.FailCodeNone.
3✔
3817
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
3✔
3818
                fwdPkg.ID(), decodeReqs, reforward,
3✔
3819
        )
3✔
3820
        if sphinxErr != nil {
3✔
3821
                l.failf(LinkFailureError{code: ErrInternalError},
×
3822
                        "unable to decode hop iterators: %v", sphinxErr)
×
3823
                return
×
3824
        }
×
3825

3826
        var switchPackets []*htlcPacket
3✔
3827

3✔
3828
        for i, update := range unackedAdds {
6✔
3829
                idx := uint16(i)
3✔
3830
                sourceRef := fwdPkg.SourceRef(idx)
3✔
3831
                add := *update
3✔
3832

3✔
3833
                // An incoming HTLC add has been full-locked in. As a result we
3✔
3834
                // can now examine the forwarding details of the HTLC, and the
3✔
3835
                // HTLC itself to decide if: we should forward it, cancel it,
3✔
3836
                // or are able to settle it (and it adheres to our fee related
3✔
3837
                // constraints).
3✔
3838

3✔
3839
                // Before adding the new htlc to the state machine, parse the
3✔
3840
                // onion object in order to obtain the routing information with
3✔
3841
                // DecodeHopIterator function which process the Sphinx packet.
3✔
3842
                chanIterator, failureCode := decodeResps[i].Result()
3✔
3843
                if failureCode != lnwire.CodeNone {
6✔
3844
                        // If we're unable to process the onion blob then we
3✔
3845
                        // should send the malformed htlc error to payment
3✔
3846
                        // sender.
3✔
3847
                        l.sendMalformedHTLCError(
3✔
3848
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
3✔
3849
                        )
3✔
3850

3✔
3851
                        l.log.Errorf("unable to decode onion hop iterator "+
3✔
3852
                                "for htlc(id=%v, hash=%x): %v", add.ID,
3✔
3853
                                add.PaymentHash, failureCode)
3✔
3854

3✔
3855
                        continue
3✔
3856
                }
3857

3858
                heightNow := l.cfg.BestHeight()
3✔
3859

3✔
3860
                pld, routeRole, pldErr := chanIterator.HopPayload()
3✔
3861
                if pldErr != nil {
6✔
3862
                        // If we're unable to process the onion payload, or we
3✔
3863
                        // received invalid onion payload failure, then we
3✔
3864
                        // should send an error back to the caller so the HTLC
3✔
3865
                        // can be canceled.
3✔
3866
                        var failedType uint64
3✔
3867

3✔
3868
                        // We need to get the underlying error value, so we
3✔
3869
                        // can't use errors.As as suggested by the linter.
3✔
3870
                        //nolint:errorlint
3✔
3871
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
3✔
3872
                                failedType = uint64(e.Type)
×
3873
                        }
×
3874

3875
                        // If we couldn't parse the payload, make our best
3876
                        // effort at creating an error encrypter that knows
3877
                        // what blinding type we were, but if we couldn't
3878
                        // parse the payload we have no way of knowing whether
3879
                        // we were the introduction node or not.
3880
                        //
3881
                        //nolint:ll
3882
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
3✔
3883
                                l.cfg.ExtractErrorEncrypter,
3✔
3884
                                // We need our route role here because we
3✔
3885
                                // couldn't parse or validate the payload.
3✔
3886
                                routeRole == hop.RouteRoleIntroduction,
3✔
3887
                        )
3✔
3888
                        if failCode != lnwire.CodeNone {
3✔
3889
                                l.log.Errorf("could not extract error "+
×
3890
                                        "encrypter: %v", pldErr)
×
3891

×
3892
                                // We can't process this htlc, send back
×
3893
                                // malformed.
×
3894
                                l.sendMalformedHTLCError(
×
3895
                                        add.ID, failureCode, add.OnionBlob,
×
3896
                                        &sourceRef,
×
3897
                                )
×
3898

×
3899
                                continue
×
3900
                        }
3901

3902
                        // TODO: currently none of the test unit infrastructure
3903
                        // is setup to handle TLV payloads, so testing this
3904
                        // would require implementing a separate mock iterator
3905
                        // for TLV payloads that also supports injecting invalid
3906
                        // payloads. Deferring this non-trival effort till a
3907
                        // later date
3908
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
3✔
3909

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

3✔
3915
                        l.log.Errorf("unable to decode forwarding "+
3✔
3916
                                "instructions: %v", pldErr)
3✔
3917

3✔
3918
                        continue
3✔
3919
                }
3920

3921
                // Retrieve onion obfuscator from onion blob in order to
3922
                // produce initial obfuscation of the onion failureCode.
3923
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
3✔
3924
                        l.cfg.ExtractErrorEncrypter,
3✔
3925
                        routeRole == hop.RouteRoleIntroduction,
3✔
3926
                )
3✔
3927
                if failureCode != lnwire.CodeNone {
3✔
3928
                        // If we're unable to process the onion blob than we
×
3929
                        // should send the malformed htlc error to payment
×
3930
                        // sender.
×
3931
                        l.sendMalformedHTLCError(
×
3932
                                add.ID, failureCode, add.OnionBlob,
×
3933
                                &sourceRef,
×
3934
                        )
×
3935

×
3936
                        l.log.Errorf("unable to decode onion "+
×
3937
                                "obfuscator: %v", failureCode)
×
3938

×
3939
                        continue
×
3940
                }
3941

3942
                fwdInfo := pld.ForwardingInfo()
3✔
3943

3✔
3944
                // Check whether the payload we've just processed uses our
3✔
3945
                // node as the introduction point (gave us a blinding key in
3✔
3946
                // the payload itself) and fail it back if we don't support
3✔
3947
                // route blinding.
3✔
3948
                if fwdInfo.NextBlinding.IsSome() &&
3✔
3949
                        l.cfg.DisallowRouteBlinding {
6✔
3950

3✔
3951
                        failure := lnwire.NewInvalidBlinding(
3✔
3952
                                fn.Some(add.OnionBlob),
3✔
3953
                        )
3✔
3954

3✔
3955
                        l.sendHTLCError(
3✔
3956
                                add, sourceRef, NewLinkError(failure),
3✔
3957
                                obfuscator, false,
3✔
3958
                        )
3✔
3959

3✔
3960
                        l.log.Error("rejected htlc that uses use as an " +
3✔
3961
                                "introduction point when we do not support " +
3✔
3962
                                "route blinding")
3✔
3963

3✔
3964
                        continue
3✔
3965
                }
3966

3967
                switch fwdInfo.NextHop {
3✔
3968
                case hop.Exit:
3✔
3969
                        err := l.processExitHop(
3✔
3970
                                add, sourceRef, obfuscator, fwdInfo,
3✔
3971
                                heightNow, pld,
3✔
3972
                        )
3✔
3973
                        if err != nil {
3✔
3974
                                l.failf(LinkFailureError{
×
3975
                                        code: ErrInternalError,
×
3976
                                }, err.Error()) //nolint
×
3977

×
3978
                                return
×
3979
                        }
×
3980

3981
                // There are additional channels left within this route. So
3982
                // we'll simply do some forwarding package book-keeping.
3983
                default:
3✔
3984
                        // If hodl.AddIncoming is requested, we will not
3✔
3985
                        // validate the forwarded ADD, nor will we send the
3✔
3986
                        // packet to the htlc switch.
3✔
3987
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
3✔
3988
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3989
                                continue
×
3990
                        }
3991

3992
                        endorseValue := l.experimentalEndorsement(
3✔
3993
                                record.CustomSet(add.CustomRecords),
3✔
3994
                        )
3✔
3995
                        endorseType := uint64(
3✔
3996
                                lnwire.ExperimentalEndorsementType,
3✔
3997
                        )
3✔
3998

3✔
3999
                        switch fwdPkg.State {
3✔
4000
                        case channeldb.FwdStateProcessed:
3✔
4001
                                // This add was not forwarded on the previous
3✔
4002
                                // processing phase, run it through our
3✔
4003
                                // validation pipeline to reproduce an error.
3✔
4004
                                // This may trigger a different error due to
3✔
4005
                                // expiring timelocks, but we expect that an
3✔
4006
                                // error will be reproduced.
3✔
4007
                                if !fwdPkg.FwdFilter.Contains(idx) {
3✔
4008
                                        break
×
4009
                                }
4010

4011
                                // Otherwise, it was already processed, we can
4012
                                // can collect it and continue.
4013
                                outgoingAdd := &lnwire.UpdateAddHTLC{
3✔
4014
                                        Expiry:        fwdInfo.OutgoingCTLV,
3✔
4015
                                        Amount:        fwdInfo.AmountToForward,
3✔
4016
                                        PaymentHash:   add.PaymentHash,
3✔
4017
                                        BlindingPoint: fwdInfo.NextBlinding,
3✔
4018
                                }
3✔
4019

3✔
4020
                                endorseValue.WhenSome(func(e byte) {
6✔
4021
                                        custRecords := map[uint64][]byte{
3✔
4022
                                                endorseType: {e},
3✔
4023
                                        }
3✔
4024

3✔
4025
                                        outgoingAdd.CustomRecords = custRecords
3✔
4026
                                })
3✔
4027

4028
                                // Finally, we'll encode the onion packet for
4029
                                // the _next_ hop using the hop iterator
4030
                                // decoded for the current hop.
4031
                                buf := bytes.NewBuffer(
3✔
4032
                                        outgoingAdd.OnionBlob[0:0],
3✔
4033
                                )
3✔
4034

3✔
4035
                                // We know this cannot fail, as this ADD
3✔
4036
                                // was marked forwarded in a previous
3✔
4037
                                // round of processing.
3✔
4038
                                chanIterator.EncodeNextHop(buf)
3✔
4039

3✔
4040
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
4041

3✔
4042
                                //nolint:ll
3✔
4043
                                updatePacket := &htlcPacket{
3✔
4044
                                        incomingChanID:       l.ShortChanID(),
3✔
4045
                                        incomingHTLCID:       add.ID,
3✔
4046
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
4047
                                        sourceRef:            &sourceRef,
3✔
4048
                                        incomingAmount:       add.Amount,
3✔
4049
                                        amount:               outgoingAdd.Amount,
3✔
4050
                                        htlc:                 outgoingAdd,
3✔
4051
                                        obfuscator:           obfuscator,
3✔
4052
                                        incomingTimeout:      add.Expiry,
3✔
4053
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
4054
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
4055
                                        inboundFee:           inboundFee,
3✔
4056
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
4057
                                }
3✔
4058
                                switchPackets = append(
3✔
4059
                                        switchPackets, updatePacket,
3✔
4060
                                )
3✔
4061

3✔
4062
                                continue
3✔
4063
                        }
4064

4065
                        // TODO(roasbeef): ensure don't accept outrageous
4066
                        // timeout for htlc
4067

4068
                        // With all our forwarding constraints met, we'll
4069
                        // create the outgoing HTLC using the parameters as
4070
                        // specified in the forwarding info.
4071
                        addMsg := &lnwire.UpdateAddHTLC{
3✔
4072
                                Expiry:        fwdInfo.OutgoingCTLV,
3✔
4073
                                Amount:        fwdInfo.AmountToForward,
3✔
4074
                                PaymentHash:   add.PaymentHash,
3✔
4075
                                BlindingPoint: fwdInfo.NextBlinding,
3✔
4076
                        }
3✔
4077

3✔
4078
                        endorseValue.WhenSome(func(e byte) {
6✔
4079
                                addMsg.CustomRecords = map[uint64][]byte{
3✔
4080
                                        endorseType: {e},
3✔
4081
                                }
3✔
4082
                        })
3✔
4083

4084
                        // Finally, we'll encode the onion packet for the
4085
                        // _next_ hop using the hop iterator decoded for the
4086
                        // current hop.
4087
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
3✔
4088
                        err := chanIterator.EncodeNextHop(buf)
3✔
4089
                        if err != nil {
3✔
4090
                                l.log.Errorf("unable to encode the "+
×
4091
                                        "remaining route %v", err)
×
4092

×
4093
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
4094
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
4095
                                }
×
4096

4097
                                failure := l.createFailureWithUpdate(
×
4098
                                        true, hop.Source, cb,
×
4099
                                )
×
4100

×
4101
                                l.sendHTLCError(
×
4102
                                        add, sourceRef, NewLinkError(failure),
×
4103
                                        obfuscator, false,
×
4104
                                )
×
4105
                                continue
×
4106
                        }
4107

4108
                        // Now that this add has been reprocessed, only append
4109
                        // it to our list of packets to forward to the switch
4110
                        // this is the first time processing the add. If the
4111
                        // fwd pkg has already been processed, then we entered
4112
                        // the above section to recreate a previous error.  If
4113
                        // the packet had previously been forwarded, it would
4114
                        // have been added to switchPackets at the top of this
4115
                        // section.
4116
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
6✔
4117
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
4118

3✔
4119
                                //nolint:ll
3✔
4120
                                updatePacket := &htlcPacket{
3✔
4121
                                        incomingChanID:       l.ShortChanID(),
3✔
4122
                                        incomingHTLCID:       add.ID,
3✔
4123
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
4124
                                        sourceRef:            &sourceRef,
3✔
4125
                                        incomingAmount:       add.Amount,
3✔
4126
                                        amount:               addMsg.Amount,
3✔
4127
                                        htlc:                 addMsg,
3✔
4128
                                        obfuscator:           obfuscator,
3✔
4129
                                        incomingTimeout:      add.Expiry,
3✔
4130
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
4131
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
4132
                                        inboundFee:           inboundFee,
3✔
4133
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
4134
                                }
3✔
4135

3✔
4136
                                fwdPkg.FwdFilter.Set(idx)
3✔
4137
                                switchPackets = append(switchPackets,
3✔
4138
                                        updatePacket)
3✔
4139
                        }
3✔
4140
                }
4141
        }
4142

4143
        // Commit the htlcs we are intending to forward if this package has not
4144
        // been fully processed.
4145
        if fwdPkg.State == channeldb.FwdStateLockedIn {
6✔
4146
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
3✔
4147
                if err != nil {
3✔
4148
                        l.failf(LinkFailureError{code: ErrInternalError},
×
4149
                                "unable to set fwd filter: %v", err)
×
4150
                        return
×
4151
                }
×
4152
        }
4153

4154
        if len(switchPackets) == 0 {
6✔
4155
                return
3✔
4156
        }
3✔
4157

4158
        l.log.Debugf("forwarding %d packets to switch: reforward=%v",
3✔
4159
                len(switchPackets), reforward)
3✔
4160

3✔
4161
        // NOTE: This call is made synchronous so that we ensure all circuits
3✔
4162
        // are committed in the exact order that they are processed in the link.
3✔
4163
        // Failing to do this could cause reorderings/gaps in the range of
3✔
4164
        // opened circuits, which violates assumptions made by the circuit
3✔
4165
        // trimming.
3✔
4166
        l.forwardBatch(reforward, switchPackets...)
3✔
4167
}
4168

4169
// experimentalEndorsement returns the value to set for our outgoing
4170
// experimental endorsement field, and a boolean indicating whether it should
4171
// be populated on the outgoing htlc.
4172
func (l *channelLink) experimentalEndorsement(
4173
        customUpdateAdd record.CustomSet) fn.Option[byte] {
3✔
4174

3✔
4175
        // Only relay experimental signal if we are within the experiment
3✔
4176
        // period.
3✔
4177
        if !l.cfg.ShouldFwdExpEndorsement() {
6✔
4178
                return fn.None[byte]()
3✔
4179
        }
3✔
4180

4181
        // If we don't have any custom records or the experimental field is
4182
        // not set, just forward a zero value.
4183
        if len(customUpdateAdd) == 0 {
6✔
4184
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
4185
        }
3✔
4186

4187
        t := uint64(lnwire.ExperimentalEndorsementType)
3✔
4188
        value, set := customUpdateAdd[t]
3✔
4189
        if !set {
3✔
4190
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4191
        }
×
4192

4193
        // We expect at least one byte for this field, consider it invalid if
4194
        // it has no data and just forward a zero value.
4195
        if len(value) == 0 {
3✔
4196
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4197
        }
×
4198

4199
        // Only forward endorsed if the incoming link is endorsed.
4200
        if value[0] == lnwire.ExperimentalEndorsed {
6✔
4201
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
3✔
4202
        }
3✔
4203

4204
        // Forward as unendorsed otherwise, including cases where we've
4205
        // received an invalid value that uses more than 3 bits of information.
4206
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
4207
}
4208

4209
// processExitHop handles an htlc for which this link is the exit hop. It
4210
// returns a boolean indicating whether the commitment tx needs an update.
4211
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
4212
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
4213
        fwdInfo hop.ForwardingInfo, heightNow uint32,
4214
        payload invoices.Payload) error {
3✔
4215

3✔
4216
        // If hodl.ExitSettle is requested, we will not validate the final hop's
3✔
4217
        // ADD, nor will we settle the corresponding invoice or respond with the
3✔
4218
        // preimage.
3✔
4219
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
6✔
4220
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
3✔
4221
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
3✔
4222

3✔
4223
                return nil
3✔
4224
        }
3✔
4225

4226
        // In case the traffic shaper is active, we'll check if the HTLC has
4227
        // custom records and skip the amount check in the onion payload below.
4228
        isCustomHTLC := fn.MapOptionZ(
3✔
4229
                l.cfg.AuxTrafficShaper,
3✔
4230
                func(ts AuxTrafficShaper) bool {
3✔
4231
                        return ts.IsCustomHTLC(add.CustomRecords)
×
4232
                },
×
4233
        )
4234

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

×
4244
                failure := NewLinkError(
×
4245
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
×
4246
                )
×
4247
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
×
4248

×
4249
                return nil
×
4250
        }
×
4251

4252
        // We'll also ensure that our time-lock value has been computed
4253
        // correctly.
4254
        if add.Expiry < fwdInfo.OutgoingCTLV {
3✔
4255
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
×
4256
                        "incompatible time-lock: expected <=%v, got %v",
×
4257
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
×
4258

×
4259
                failure := NewLinkError(
×
4260
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
×
4261
                )
×
4262

×
4263
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
×
4264

×
4265
                return nil
×
4266
        }
×
4267

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

3✔
4273
        circuitKey := models.CircuitKey{
3✔
4274
                ChanID: l.ShortChanID(),
3✔
4275
                HtlcID: add.ID,
3✔
4276
        }
3✔
4277

3✔
4278
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
3✔
4279
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
3✔
4280
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
3✔
4281
        )
3✔
4282
        if err != nil {
3✔
4283
                return err
×
4284
        }
×
4285

4286
        // Create a hodlHtlc struct and decide either resolved now or later.
4287
        htlc := hodlHtlc{
3✔
4288
                add:        add,
3✔
4289
                sourceRef:  sourceRef,
3✔
4290
                obfuscator: obfuscator,
3✔
4291
        }
3✔
4292

3✔
4293
        // If the event is nil, the invoice is being held, so we save payment
3✔
4294
        // descriptor for future reference.
3✔
4295
        if event == nil {
6✔
4296
                l.hodlMap[circuitKey] = htlc
3✔
4297
                return nil
3✔
4298
        }
3✔
4299

4300
        // Process the received resolution.
4301
        return l.processHtlcResolution(event, htlc)
3✔
4302
}
4303

4304
// settleHTLC settles the HTLC on the channel.
4305
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
4306
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
3✔
4307

3✔
4308
        hash := preimage.Hash()
3✔
4309

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

3✔
4312
        err := l.channel.SettleHTLC(
3✔
4313
                preimage, htlcIndex, &sourceRef, nil, nil,
3✔
4314
        )
3✔
4315
        if err != nil {
3✔
4316
                return fmt.Errorf("unable to settle htlc: %w", err)
×
4317
        }
×
4318

4319
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
4320
        // fake one before sending it to the peer.
4321
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
6✔
4322
                l.log.Warnf(hodl.BogusSettle.Warning())
3✔
4323
                preimage = [32]byte{}
3✔
4324
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
3✔
4325
        }
3✔
4326

4327
        // HTLC was successfully settled locally send notification about it
4328
        // remote peer.
4329
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
3✔
4330
                ChanID:          l.ChanID(),
3✔
4331
                ID:              htlcIndex,
3✔
4332
                PaymentPreimage: preimage,
3✔
4333
        })
3✔
4334

3✔
4335
        // Once we have successfully settled the htlc, notify a settle event.
3✔
4336
        l.cfg.HtlcNotifier.NotifySettleEvent(
3✔
4337
                HtlcKey{
3✔
4338
                        IncomingCircuit: models.CircuitKey{
3✔
4339
                                ChanID: l.ShortChanID(),
3✔
4340
                                HtlcID: htlcIndex,
3✔
4341
                        },
3✔
4342
                },
3✔
4343
                preimage,
3✔
4344
                HtlcEventTypeReceive,
3✔
4345
        )
3✔
4346

3✔
4347
        return nil
3✔
4348
}
4349

4350
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
4351
// err chan for the individual responses. This method is intended to be spawned
4352
// as a goroutine so the responses can be handled in the background.
4353
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
3✔
4354
        // Don't forward packets for which we already have a response in our
3✔
4355
        // mailbox. This could happen if a packet fails and is buffered in the
3✔
4356
        // mailbox, and the incoming link flaps.
3✔
4357
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
3✔
4358
        for _, pkt := range packets {
6✔
4359
                if l.mailBox.HasPacket(pkt.inKey()) {
6✔
4360
                        continue
3✔
4361
                }
4362

4363
                filteredPkts = append(filteredPkts, pkt)
3✔
4364
        }
4365

4366
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
3✔
4367
        if err != nil {
3✔
4368
                log.Errorf("Unhandled error while reforwarding htlc "+
×
4369
                        "settle/fail over htlcswitch: %v", err)
×
4370
        }
×
4371
}
4372

4373
// sendHTLCError functions cancels HTLC and send cancel message back to the
4374
// peer from which HTLC was received.
4375
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
4376
        sourceRef channeldb.AddRef, failure *LinkError,
4377
        e hop.ErrorEncrypter, isReceive bool) {
3✔
4378

3✔
4379
        reason, err := e.EncryptFirstHop(failure.WireMessage())
3✔
4380
        if err != nil {
3✔
4381
                l.log.Errorf("unable to obfuscate error: %v", err)
×
4382
                return
×
4383
        }
×
4384

4385
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
3✔
4386
        if err != nil {
3✔
4387
                l.log.Errorf("unable cancel htlc: %v", err)
×
4388
                return
×
4389
        }
×
4390

4391
        // Send the appropriate failure message depending on whether we're
4392
        // in a blinded route or not.
4393
        if err := l.sendIncomingHTLCFailureMsg(
3✔
4394
                add.ID, e, reason,
3✔
4395
        ); err != nil {
3✔
4396
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
4397
                return
×
4398
        }
×
4399

4400
        // Notify a link failure on our incoming link. Outgoing htlc information
4401
        // is not available at this point, because we have not decrypted the
4402
        // onion, so it is excluded.
4403
        var eventType HtlcEventType
3✔
4404
        if isReceive {
6✔
4405
                eventType = HtlcEventTypeReceive
3✔
4406
        } else {
6✔
4407
                eventType = HtlcEventTypeForward
3✔
4408
        }
3✔
4409

4410
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
3✔
4411
                HtlcKey{
3✔
4412
                        IncomingCircuit: models.CircuitKey{
3✔
4413
                                ChanID: l.ShortChanID(),
3✔
4414
                                HtlcID: add.ID,
3✔
4415
                        },
3✔
4416
                },
3✔
4417
                HtlcInfo{
3✔
4418
                        IncomingTimeLock: add.Expiry,
3✔
4419
                        IncomingAmt:      add.Amount,
3✔
4420
                },
3✔
4421
                eventType,
3✔
4422
                failure,
3✔
4423
                true,
3✔
4424
        )
3✔
4425
}
4426

4427
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
4428
// peer from which the HTLC was received. This function is primarily used to
4429
// handle the special requirements of route blinding, specifically:
4430
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
4431
// - Introduction nodes should return regular HTLC failure messages.
4432
//
4433
// It accepts the original opaque failure, which will be used in the case
4434
// that we're not part of a blinded route and an error encrypter that'll be
4435
// used if we are the introduction node and need to present an error as if
4436
// we're the failing party.
4437
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
4438
        e hop.ErrorEncrypter,
4439
        originalFailure lnwire.OpaqueReason) error {
3✔
4440

3✔
4441
        var msg lnwire.Message
3✔
4442
        switch {
3✔
4443
        // Our circuit's error encrypter will be nil if this was a locally
4444
        // initiated payment. We can only hit a blinded error for a locally
4445
        // initiated payment if we allow ourselves to be picked as the
4446
        // introduction node for our own payments and in that case we
4447
        // shouldn't reach this code. To prevent the HTLC getting stuck,
4448
        // we fail it back and log an error.
4449
        // code.
4450
        case e == nil:
×
4451
                msg = &lnwire.UpdateFailHTLC{
×
4452
                        ChanID: l.ChanID(),
×
4453
                        ID:     htlcIndex,
×
4454
                        Reason: originalFailure,
×
4455
                }
×
4456

×
4457
                l.log.Errorf("Unexpected blinded failure when "+
×
4458
                        "we are the sending node, incoming htlc: %v(%v)",
×
4459
                        l.ShortChanID(), htlcIndex)
×
4460

4461
        // For cleartext hops (ie, non-blinded/normal) we don't need any
4462
        // transformation on the error message and can just send the original.
4463
        case !e.Type().IsBlinded():
3✔
4464
                msg = &lnwire.UpdateFailHTLC{
3✔
4465
                        ChanID: l.ChanID(),
3✔
4466
                        ID:     htlcIndex,
3✔
4467
                        Reason: originalFailure,
3✔
4468
                }
3✔
4469

4470
        // When we're the introduction node, we need to convert the error to
4471
        // a UpdateFailHTLC.
4472
        case e.Type() == hop.EncrypterTypeIntroduction:
3✔
4473
                l.log.Debugf("Introduction blinded node switching out failure "+
3✔
4474
                        "error: %v", htlcIndex)
3✔
4475

3✔
4476
                // The specification does not require that we set the onion
3✔
4477
                // blob.
3✔
4478
                failureMsg := lnwire.NewInvalidBlinding(
3✔
4479
                        fn.None[[lnwire.OnionPacketSize]byte](),
3✔
4480
                )
3✔
4481
                reason, err := e.EncryptFirstHop(failureMsg)
3✔
4482
                if err != nil {
3✔
4483
                        return err
×
4484
                }
×
4485

4486
                msg = &lnwire.UpdateFailHTLC{
3✔
4487
                        ChanID: l.ChanID(),
3✔
4488
                        ID:     htlcIndex,
3✔
4489
                        Reason: reason,
3✔
4490
                }
3✔
4491

4492
        // If we are a relaying node, we need to switch out any error that
4493
        // we've received to a malformed HTLC error.
4494
        case e.Type() == hop.EncrypterTypeRelaying:
3✔
4495
                l.log.Debugf("Relaying blinded node switching out malformed "+
3✔
4496
                        "error: %v", htlcIndex)
3✔
4497

3✔
4498
                msg = &lnwire.UpdateFailMalformedHTLC{
3✔
4499
                        ChanID:      l.ChanID(),
3✔
4500
                        ID:          htlcIndex,
3✔
4501
                        FailureCode: lnwire.CodeInvalidBlinding,
3✔
4502
                }
3✔
4503

4504
        default:
×
4505
                return fmt.Errorf("unexpected encrypter: %d", e)
×
4506
        }
4507

4508
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
4509
                l.log.Warnf("Send update fail failed: %v", err)
×
4510
        }
×
4511

4512
        return nil
3✔
4513
}
4514

4515
// sendMalformedHTLCError helper function which sends the malformed HTLC update
4516
// to the payment sender.
4517
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
4518
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
4519
        sourceRef *channeldb.AddRef) {
3✔
4520

3✔
4521
        shaOnionBlob := sha256.Sum256(onionBlob[:])
3✔
4522
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
3✔
4523
        if err != nil {
3✔
4524
                l.log.Errorf("unable cancel htlc: %v", err)
×
4525
                return
×
4526
        }
×
4527

4528
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
3✔
4529
                ChanID:       l.ChanID(),
3✔
4530
                ID:           htlcIndex,
3✔
4531
                ShaOnionBlob: shaOnionBlob,
3✔
4532
                FailureCode:  code,
3✔
4533
        })
3✔
4534
}
4535

4536
// failf is a function which is used to encapsulate the action necessary for
4537
// properly failing the link. It takes a LinkFailureError, which will be passed
4538
// to the OnChannelFailure closure, in order for it to determine if we should
4539
// force close the channel, and if we should send an error message to the
4540
// remote peer.
4541
func (l *channelLink) failf(linkErr LinkFailureError, format string,
4542
        a ...interface{}) {
3✔
4543

3✔
4544
        reason := fmt.Errorf(format, a...)
3✔
4545

3✔
4546
        // Return if we have already notified about a failure.
3✔
4547
        if l.failed {
6✔
4548
                l.log.Warnf("ignoring link failure (%v), as link already "+
3✔
4549
                        "failed", reason)
3✔
4550
                return
3✔
4551
        }
3✔
4552

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

3✔
4555
        // Set failed, such that we won't process any more updates, and notify
3✔
4556
        // the peer about the failure.
3✔
4557
        l.failed = true
3✔
4558
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
3✔
4559
}
4560

4561
// FundingCustomBlob returns the custom funding blob of the channel that this
4562
// link is associated with. The funding blob represents static information about
4563
// the channel that was created at channel funding time.
4564
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
4565
        if l.channel == nil {
×
4566
                return fn.None[tlv.Blob]()
×
4567
        }
×
4568

4569
        if l.channel.State() == nil {
×
4570
                return fn.None[tlv.Blob]()
×
4571
        }
×
4572

4573
        return l.channel.State().CustomBlob
×
4574
}
4575

4576
// CommitmentCustomBlob returns the custom blob of the current local commitment
4577
// of the channel that this link is associated with.
4578
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
4579
        if l.channel == nil {
×
4580
                return fn.None[tlv.Blob]()
×
4581
        }
×
4582

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