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

lightningnetwork / lnd / 16032370868

02 Jul 2025 05:59PM UTC coverage: 67.589% (+0.05%) from 67.54%
16032370868

push

github

web-flow
Merge pull request #10017 from ellemouton/strictTypeForChanFeatures

refactor+multi: use *lnwire.FeatureVector for ChannelEdgeInfo features

16 of 31 new or added lines in 5 files covered. (51.61%)

41 existing lines in 13 files now uncovered.

135179 of 200001 relevant lines covered (67.59%)

21871.33 hits per line

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

77.76
/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() {
16✔
40
        prand.Seed(time.Now().UnixNano())
16✔
41
}
16✔
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 {
81✔
81

81✔
82
        return f.BaseFee + (htlcAmt*f.FeeRate)/1000000
81✔
83
}
81✔
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 {
648✔
440
        return hookMap{
648✔
441
                allocIdx:      atomic.Uint64{},
648✔
442
                transient:     make(map[uint64]func()),
648✔
443
                newTransients: make(chan func()),
648✔
444
        }
648✔
445
}
648✔
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 {
5✔
451
        // We assume we never overflow a uint64. Seems OK.
5✔
452
        hookID := m.allocIdx.Add(1)
5✔
453
        if hookID == 0 {
5✔
454
                panic("hookMap allocIdx overflow")
×
455
        }
456
        m.transient[hookID] = hook
5✔
457

5✔
458
        return hookID
5✔
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() {
2,770✔
464
        for _, hook := range m.transient {
2,775✔
465
                hook()
5✔
466
        }
5✔
467

468
        m.transient = make(map[uint64]func())
2,770✔
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 {
218✔
482

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

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

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

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

218✔
513
        return &channelLink{
218✔
514
                cfg:                 cfg,
218✔
515
                channel:             channel,
218✔
516
                hodlMap:             make(map[models.CircuitKey]hodlHtlc),
218✔
517
                hodlQueue:           queue.NewConcurrentQueue(10),
218✔
518
                log:                 log.WithPrefix(logPrefix),
218✔
519
                flushHooks:          newHookMap(),
218✔
520
                outgoingCommitHooks: newHookMap(),
218✔
521
                incomingCommitHooks: newHookMap(),
218✔
522
                quiescer:            qsm,
218✔
523
                quiescenceReqs:      quiescenceReqs,
218✔
524
                cg:                  fn.NewContextGuard(),
218✔
525
        }
218✔
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 {
216✔
537
        if !atomic.CompareAndSwapInt32(&l.started, 0, 1) {
216✔
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")
216✔
544

216✔
545
        // If the config supplied watchtower client, ensure the channel is
216✔
546
        // registered before trying to use it during operation.
216✔
547
        if l.cfg.TowerClient != nil {
219✔
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()
216✔
557
        l.hodlQueue.Start()
216✔
558

216✔
559
        // Before launching the htlcManager messages, revert any circuits that
216✔
560
        // were marked open in the switch's circuit map, but did not make it
216✔
561
        // into a commitment txn. We use the next local htlc index as the cut
216✔
562
        // off point, since all indexes below that are committed. This action
216✔
563
        // is only performed if the link's final short channel ID has been
216✔
564
        // assigned, otherwise we would try to trim the htlcs belonging to the
216✔
565
        // all-zero, hop.Source ID.
216✔
566
        if l.ShortChanID() != hop.Source {
432✔
567
                localHtlcIndex, err := l.channel.NextLocalHtlcIndex()
216✔
568
                if err != nil {
216✔
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()
216✔
578
                err = l.cfg.Circuits.TrimOpenCircuits(chanID, localHtlcIndex)
216✔
579
                if err != nil {
216✔
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() {
432✔
590
                        signals := &contractcourt.ContractSignals{
216✔
591
                                ShortChanID: l.channel.ShortChanID(),
216✔
592
                        }
216✔
593

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

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

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

216✔
606
        return nil
216✔
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() {
217✔
614
        if !atomic.CompareAndSwapInt32(&l.shutdown, 0, 1) {
229✔
615
                l.log.Warn("already stopped")
12✔
616
                return
12✔
617
        }
12✔
618

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

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

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

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

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

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

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

205✔
653
        // As a final precaution, we will attempt to flush any uncommitted
205✔
654
        // preimages to the preimage cache. The preimages should be re-delivered
205✔
655
        // after channel reestablishment, however this adds an extra layer of
205✔
656
        // protection in case the peer never returns. Without this, we will be
205✔
657
        // unable to settle any contracts depending on the preimages even though
205✔
658
        // we had learned them at some point.
205✔
659
        err := l.cfg.PreimageCache.AddPreimages(l.uncommittedPreimages...)
205✔
660
        if err != nil {
205✔
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 {
616✔
679
        l.RLock()
616✔
680
        defer l.RUnlock()
616✔
681

616✔
682
        return l.eligibleToForward()
616✔
683
}
616✔
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 {
616✔
692
        return l.eligibleToUpdate() && !l.IsFlushing(Outgoing)
616✔
693
}
616✔
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 {
619✔
703
        return l.channel.RemoteNextRevocation() != nil &&
619✔
704
                l.channel.ShortChanID() != hop.Source &&
619✔
705
                l.isReestablished() &&
619✔
706
                l.quiescer.CanSendUpdates()
619✔
707
}
619✔
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 {
19✔
713
        if linkDirection == Outgoing {
30✔
714
                return l.isOutgoingAddBlocked.Swap(false)
11✔
715
        }
11✔
716

717
        return l.isIncomingAddBlocked.Swap(false)
8✔
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 {
13✔
724
        if linkDirection == Outgoing {
20✔
725
                return !l.isOutgoingAddBlocked.Swap(true)
7✔
726
        }
7✔
727

728
        return !l.isIncomingAddBlocked.Swap(true)
9✔
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 {
1,594✔
734
        if linkDirection == Outgoing {
2,714✔
735
                return l.isOutgoingAddBlocked.Load()
1,120✔
736
        }
1,120✔
737

738
        return l.isIncomingAddBlocked.Load()
477✔
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()) {
4✔
745
        select {
4✔
746
        case l.flushHooks.newTransients <- hook:
4✔
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()) {
4✔
756
        var queue chan func()
4✔
757

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

764
        select {
4✔
765
        case queue <- hook:
4✔
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] {
4✔
778
        req, out := fn.NewReq[fn.Unit, fn.Result[lntypes.ChannelParty]](
4✔
779
                fn.Unit{},
4✔
780
        )
4✔
781

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

788
        return out
4✔
789
}
790

791
// isReestablished returns true if the link has successfully completed the
792
// channel reestablishment dance.
793
func (l *channelLink) isReestablished() bool {
619✔
794
        return atomic.LoadInt32(&l.reestablished) == 1
619✔
795
}
619✔
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() {
216✔
801
        atomic.StoreInt32(&l.reestablished, 1)
216✔
802
}
216✔
803

804
// IsUnadvertised returns true if the underlying channel is unadvertised.
805
func (l *channelLink) IsUnadvertised() bool {
5✔
806
        state := l.channel.State()
5✔
807
        return state.ChannelFlags&lnwire.FFAnnounceChannel == 0
5✔
808
}
5✔
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) {
4✔
815
        // We'll first query for the sat/kw recommended to be confirmed within 3
4✔
816
        // blocks.
4✔
817
        feePerKw, err := l.cfg.FeeEstimator.EstimateFeePerKW(3)
4✔
818
        if err != nil {
4✔
819
                return 0, err
×
820
        }
×
821

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

4✔
825
        return feePerKw, nil
4✔
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 {
14✔
834

14✔
835
        switch {
14✔
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:
1✔
840
                return true
1✔
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):
4✔
845
                return true
4✔
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):
2✔
850
                return true
2✔
851

852
        // Otherwise, we won't modify our fee.
853
        default:
7✔
854
                return false
7✔
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 {
25✔
867

25✔
868
        // Determine which SCID to use in case we need to use aliases in the
25✔
869
        // ChannelUpdate.
25✔
870
        scid := outgoingScid
25✔
871
        if incoming {
25✔
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)
25✔
878
        if update == nil {
44✔
879
                // Fallback to the non-alias behavior.
19✔
880
                var err error
19✔
881
                update, err = l.cfg.FetchLastChannelUpdate(l.ShortChanID())
19✔
882
                if err != nil {
19✔
883
                        return &lnwire.FailTemporaryNodeFailure{}
×
884
                }
×
885
        }
886

887
        return cb(update)
25✔
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 {
173✔
895
        chanState := l.channel.State()
173✔
896

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

173✔
899
        // First, we'll generate our ChanSync message to send to the other
173✔
900
        // side. Based on this message, the remote party will decide if they
173✔
901
        // need to retransmit any data or not.
173✔
902
        localChanSyncMsg, err := chanState.ChanSyncMsg()
173✔
903
        if err != nil {
173✔
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 {
173✔
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
173✔
913

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

173✔
921
                remoteChanSyncMsg, ok := msg.(*lnwire.ChannelReestablish)
173✔
922
                if !ok {
173✔
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 &&
173✔
934
                        localChanSyncMsg.NextLocalCommitHeight == 1 &&
173✔
935
                        !l.channel.IsPending() {
340✔
936

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

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

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

167✔
949
                        // If this is a taproot channel, then we'll send the
167✔
950
                        // very same nonce that we sent above, as they should
167✔
951
                        // take the latest verification nonce we send.
167✔
952
                        if chanState.ChanType.IsTaproot() {
170✔
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() {
170✔
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)
167✔
979
                        if err != nil {
167✔
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")
173✔
987

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

173✔
993
                // We've just received a ChanSync message from the remote
173✔
994
                // party, so we'll process the message  in order to determine
173✔
995
                // if we need to re-transmit any messages to the remote party.
173✔
996
                ctx, cancel := l.cg.Create(ctx)
173✔
997
                defer cancel()
173✔
998
                msgsToReSend, openedCircuits, closedCircuits, err =
173✔
999
                        l.channel.ProcessChanSyncMsg(ctx, remoteChanSyncMsg)
173✔
1000
                if err != nil {
176✔
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
173✔
1008
                l.closedCircuits = closedCircuits
173✔
1009

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

1016
                if len(msgsToReSend) > 0 {
178✔
1017
                        l.log.Infof("sending %v updates to synchronize the "+
5✔
1018
                                "state", len(msgsToReSend))
5✔
1019
                }
5✔
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 {
184✔
1025
                        l.cfg.Peer.SendMessage(false, msg)
11✔
1026
                }
11✔
1027

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

1032
        return nil
173✔
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 {
216✔
1041
        fwdPkgs, err := l.channel.LoadFwdPkgs()
216✔
1042
        if err != nil {
217✔
1043
                return err
1✔
1044
        }
1✔
1045

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

215✔
1048
        for _, fwdPkg := range fwdPkgs {
224✔
1049
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
9✔
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 {
218✔
1057
                return l.updateCommitTx(ctx)
3✔
1058
        }
3✔
1059

1060
        return nil
215✔
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 {
9✔
1067
        // Remove any completed packages to clear up space.
9✔
1068
        if fwdPkg.State == channeldb.FwdStateCompleted {
12✔
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() {
12✔
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() {
15✔
1097
                l.processRemoteAdds(fwdPkg)
6✔
1098

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

1108
        return nil
9✔
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() {
215✔
1118
        defer l.cg.WgDone()
215✔
1119

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

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

1127
        for {
446✔
1128
                select {
231✔
1129
                case <-l.cfg.FwdPkgGCTicker.Ticks():
16✔
1130
                        if err := l.loadAndRemove(); err != nil {
32✔
1131
                                l.log.Warnf("unable to remove fwd pkgs: %v",
16✔
1132
                                        err)
16✔
1133
                                continue
16✔
1134
                        }
1135
                case <-l.cg.Done():
205✔
1136
                        return
205✔
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 {
231✔
1145
        fwdPkgs, err := l.channel.LoadFwdPkgs()
231✔
1146
        if err != nil {
247✔
1147
                return err
16✔
1148
        }
16✔
1149

1150
        var removeHeights []uint64
215✔
1151
        for _, fwdPkg := range fwdPkgs {
224✔
1152
                if fwdPkg.State != channeldb.FwdStateCompleted {
18✔
1153
                        continue
9✔
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 {
430✔
1162
                return nil
215✔
1163
        }
215✔
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) {
216✔
1258
        defer func() {
423✔
1259
                l.cfg.BatchTicker.Stop()
207✔
1260
                l.cg.WgDone()
207✔
1261
                l.log.Infof("exited")
207✔
1262
        }()
207✔
1263

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

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

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

216✔
1275
        // If this isn't the first time that this channel link has been
216✔
1276
        // created, then we'll need to check to see if we need to
216✔
1277
        // re-synchronize state with the remote peer. settledHtlcs is a map of
216✔
1278
        // HTLC's that we re-settled as part of the channel state sync.
216✔
1279
        if l.cfg.SyncStates {
389✔
1280
                err := l.syncChanStates(ctx)
173✔
1281
                if err != nil {
176✔
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) {
219✔
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()
216✔
1309

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

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

216✔
1324
        // After cleaning up any memory pertaining to incoming packets, we now
216✔
1325
        // replay our forwarding packages to handle any htlcs that can be
216✔
1326
        // processed locally, or need to be forwarded out to the switch. We will
216✔
1327
        // only attempt to resolve packages if our short chan id indicates that
216✔
1328
        // the channel is not pending, otherwise we should have no htlcs to
216✔
1329
        // reforward.
216✔
1330
        if l.ShortChanID() != hop.Source {
432✔
1331
                err := l.resolveFwdPkgs(ctx)
216✔
1332
                switch err {
216✔
1333
                // No error was encountered, success.
1334
                case nil:
215✔
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:
1✔
1346
                        l.failf(LinkFailureError{code: ErrInternalError},
1✔
1347
                                "unable to resolve fwd pkgs: %v", err)
1✔
1348
                        return
1✔
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)
215✔
1355
                go l.fwdPkgGarbager()
215✔
1356
        }
1357

1358
        for {
4,413✔
1359
                // We must always check if we failed at some point processing
4,198✔
1360
                // the last update before processing the next.
4,198✔
1361
                if l.failed {
4,213✔
1362
                        l.log.Errorf("link failed, exiting htlcManager")
15✔
1363
                        return
15✔
1364
                }
15✔
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(
4,186✔
1371
                        lntypes.Local, lntypes.Remote,
4,186✔
1372
                )
4,186✔
1373
                if numUpdates > 0 {
4,689✔
1374
                        l.cfg.BatchTicker.Resume()
503✔
1375
                        l.log.Tracef("BatchTicker resumed, "+
503✔
1376
                                "NumPendingUpdates(Local, Remote)=%d",
503✔
1377
                                numUpdates,
503✔
1378
                        )
503✔
1379
                } else {
4,189✔
1380
                        l.cfg.BatchTicker.Pause()
3,686✔
1381
                        l.log.Trace("BatchTicker paused due to zero " +
3,686✔
1382
                                "NumPendingUpdates(Local, Remote)")
3,686✔
1383
                }
3,686✔
1384

1385
                select {
4,186✔
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:
4✔
1389
                        if l.channel.IsChannelClean() {
7✔
1390
                                hook()
3✔
1391
                        } else {
7✔
1392
                                l.flushHooks.alloc(hook)
4✔
1393
                        }
4✔
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:
4✔
1398
                        if !l.channel.OweCommitment() {
7✔
1399
                                hook()
3✔
1400
                        } else {
4✔
1401
                                l.outgoingCommitHooks.alloc(hook)
1✔
1402
                        }
1✔
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:
4✔
1416
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
4✔
1417

4✔
1418
                        // If we're not the initiator of the channel, don't we
4✔
1419
                        // don't control the fees, so we can ignore this.
4✔
1420
                        if !l.channel.IsInitiator() {
4✔
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()
4✔
1428
                        if err != nil {
4✔
1429
                                l.log.Errorf("unable to sample network fee: %v",
×
1430
                                        err)
×
1431
                                continue
×
1432
                        }
1433

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

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

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

1✔
1451
                                continue
1✔
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)
3✔
1457
                        if err != nil {
3✔
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():
198✔
1481
                        // Attempt to extend the remote commitment chain
198✔
1482
                        // including all the currently pending entries. If the
198✔
1483
                        // send was unsuccessful, then abandon the update,
198✔
1484
                        // waiting for the revocation window to open up.
198✔
1485
                        if !l.updateCommitTxOrFail(ctx) {
198✔
1486
                                return
×
1487
                        }
×
1488

1489
                case <-l.cfg.PendingCommitTicker.Ticks():
1✔
1490
                        l.failf(
1✔
1491
                                LinkFailureError{
1✔
1492
                                        code:          ErrRemoteUnresponsive,
1✔
1493
                                        FailureAction: LinkFailureDisconnect,
1✔
1494
                                },
1✔
1495
                                "unable to complete dance",
1✔
1496
                        )
1✔
1497
                        return
1✔
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:
524✔
1503
                        l.handleDownstreamPkt(ctx, pkt)
524✔
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,208✔
1509
                        l.handleUpstreamMsg(ctx, msg)
3,208✔
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():
58✔
1514
                        htlcResolution := hodlItem.(invoices.HtlcResolution)
58✔
1515
                        err := l.processHodlQueue(ctx, htlcResolution)
58✔
1516
                        switch err {
58✔
1517
                        // No error, success.
1518
                        case nil:
57✔
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:
1✔
1532
                                l.failf(LinkFailureError{
1✔
1533
                                        code: ErrInternalError,
1✔
1534
                                }, "process hodl queue: unable to update "+
1✔
1535
                                        "commitment: %v", err,
1✔
1536
                                )
1✔
1537
                        }
1538

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

4✔
1542
                        if l.noDanglingUpdates(lntypes.Local) {
8✔
1543
                                err := l.quiescer.SendOwedStfu()
4✔
1544
                                if err != nil {
4✔
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():
193✔
1554
                        return
193✔
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 {
58✔
1564

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

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

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

58✔
1585
                select {
58✔
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:
58✔
1594
                        break loop
58✔
1595
                }
1596
        }
1597

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

1603
        return nil
57✔
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 {
204✔
1611

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

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

200✔
1623
                return l.settleHTLC(
200✔
1624
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
200✔
1625
                )
200✔
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:
7✔
1630
                l.log.Debugf("received cancel resolution for "+
7✔
1631
                        "%v with outcome: %v", circuitKey, res.Outcome)
7✔
1632

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

7✔
1637
                l.sendHTLCError(
7✔
1638
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
7✔
1639
                        true,
7✔
1640
                )
7✔
1641
                return nil
7✔
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 {
7✔
1655

7✔
1656
        // If the resolution has been resolved as part of a MPP timeout,
7✔
1657
        // we need to fail the htlc with lnwire.FailMppTimeout.
7✔
1658
        if resolution.Outcome == invoices.ResultMppTimeout {
7✔
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(
7✔
1669
                amount, uint32(resolution.AcceptHeight),
7✔
1670
        )
7✔
1671

7✔
1672
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
7✔
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 {
220✔
1679
        lower := int64(l.cfg.MinUpdateTimeout)
220✔
1680
        upper := int64(l.cfg.MaxUpdateTimeout)
220✔
1681
        return time.Duration(prand.Int63n(upper-lower) + lower)
220✔
1682
}
220✔
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 {
483✔
1688

483✔
1689
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
483✔
1690
        if !ok {
483✔
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() {
483✔
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) {
483✔
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) {
487✔
1718
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1719
                        "exposure exceeded")
4✔
1720

4✔
1721
                l.mailBox.FailAdd(pkt)
4✔
1722

4✔
1723
                return NewDetailedLinkError(
4✔
1724
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1725
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1726
                )
4✔
1727
        }
4✔
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()
479✔
1733
        openCircuitRef := pkt.inKey()
479✔
1734

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

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

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

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

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

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

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

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

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

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

478✔
1794
        return nil
478✔
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) {
524✔
1805

524✔
1806
        if pkt.htlc.MsgType().IsChannelUpdate() &&
524✔
1807
                !l.quiescer.CanSendUpdates() {
524✔
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) {
524✔
1816
        case *lnwire.UpdateAddHTLC:
483✔
1817
                // Handle add message. The returned error can be ignored,
483✔
1818
                // because it is also sent through the mailbox.
483✔
1819
                _ = l.handleDownstreamUpdateAdd(ctx, pkt)
483✔
1820

1821
        case *lnwire.UpdateFulfillHTLC:
26✔
1822
                // If hodl.SettleOutgoing mode is active, we exit early to
26✔
1823
                // simulate arbitrary delays between the switch adding the
26✔
1824
                // SETTLE to the mailbox, and the HTLC being added to the
26✔
1825
                // commitment state.
26✔
1826
                if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
26✔
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()
26✔
1836
                err := l.channel.SettleHTLC(
26✔
1837
                        htlc.PaymentPreimage,
26✔
1838
                        pkt.incomingHTLCID,
26✔
1839
                        pkt.sourceRef,
26✔
1840
                        pkt.destRef,
26✔
1841
                        &inKey,
26✔
1842
                )
26✔
1843
                if err != nil {
26✔
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: "+
26✔
1864
                        "%s->%s", pkt.inKey(), pkt.outKey())
26✔
1865

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

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

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

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

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

1888
        case *lnwire.UpdateFailHTLC:
21✔
1889
                // If hodl.FailOutgoing mode is active, we exit early to
21✔
1890
                // simulate arbitrary delays between the switch adding a FAIL to
21✔
1891
                // the mailbox, and the HTLC being added to the commitment
21✔
1892
                // state.
21✔
1893
                if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
21✔
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()
21✔
1902
                err := l.channel.FailHTLC(
21✔
1903
                        pkt.incomingHTLCID,
21✔
1904
                        htlc.Reason,
21✔
1905
                        pkt.sourceRef,
21✔
1906
                        pkt.destRef,
21✔
1907
                        &inKey,
21✔
1908
                )
21✔
1909
                if err != nil {
26✔
1910
                        l.log.Errorf("unable to cancel incoming HTLC for "+
5✔
1911
                                "circuit-key=%v: %v", inKey, err)
5✔
1912

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

5✔
1926
                        return
5✔
1927
                }
1928

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

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

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

19✔
1941
                // We send the HTLC message to the peer which initially created
19✔
1942
                // the HTLC. If the incoming blinding point is non-nil, we
19✔
1943
                // know that we are a relaying node in a blinded path.
19✔
1944
                // Otherwise, we're either an introduction node or not part of
19✔
1945
                // a blinded path at all.
19✔
1946
                if err := l.sendIncomingHTLCFailureMsg(
19✔
1947
                        htlc.ID,
19✔
1948
                        pkt.obfuscator,
19✔
1949
                        htlc.Reason,
19✔
1950
                ); err != nil {
19✔
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 {
32✔
1962
                        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
13✔
1963
                                newHtlcKey(pkt),
13✔
1964
                                newHtlcInfo(pkt),
13✔
1965
                                getEventType(pkt),
13✔
1966
                                pkt.linkFailure,
13✔
1967
                                false,
13✔
1968
                        )
13✔
1969
                } else {
22✔
1970
                        l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
9✔
1971
                                newHtlcKey(pkt), getEventType(pkt),
9✔
1972
                        )
9✔
1973
                }
9✔
1974

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

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

1988
        l.updateCommitTxOrFail(ctx)
23✔
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) {
2✔
1996
        inKey := pkt.inKey()
2✔
1997

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

2✔
2001
        // If the htlc packet doesn't have a source reference, it is unsafe to
2✔
2002
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
2✔
2003
        if pkt.sourceRef == nil {
3✔
2004
                l.log.Errorf("unable to cleanup response for incoming "+
1✔
2005
                        "circuit-key=%v, does not contain source reference",
1✔
2006
                        inKey)
1✔
2007
                return
1✔
2008
        }
1✔
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)
1✔
2014
        if err != nil {
1✔
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 {
1✔
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)
1✔
2045

1✔
2046
        // With all known references acked, we can now safely delete the circuit
1✔
2047
        // from the switch's circuit map, as the state is no longer needed.
1✔
2048
        err = l.cfg.Circuits.DeleteCircuits(inKey)
1✔
2049
        if err != nil {
1✔
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,208✔
2062

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

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

2073
        switch msg := msg.(type) {
3,208✔
2074
        case *lnwire.UpdateAddHTLC:
453✔
2075
                if l.IsFlushing(Incoming) {
453✔
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 {
453✔
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) {
453✔
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)
453✔
2137
                if err != nil {
453✔
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), "+
453✔
2144
                        "assigning index: %v", msg.PaymentHash[:], index)
453✔
2145

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

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

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

2171
                if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
231✔
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{
228✔
2183
                        outgoingChanID: l.ShortChanID(),
228✔
2184
                        outgoingHTLCID: idx,
228✔
2185
                        htlc: &lnwire.UpdateFulfillHTLC{
228✔
2186
                                PaymentPreimage: pre,
228✔
2187
                        },
228✔
2188
                }
228✔
2189

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

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

2199
        case *lnwire.UpdateFailMalformedHTLC:
6✔
2200
                // Convert the failure type encoded within the HTLC fail
6✔
2201
                // message to the proper generic lnwire error code.
6✔
2202
                var failure lnwire.FailureMessage
6✔
2203
                switch msg.FailureCode {
6✔
2204
                case lnwire.CodeInvalidOnionVersion:
4✔
2205
                        failure = &lnwire.FailInvalidOnionVersion{
4✔
2206
                                OnionSHA256: msg.ShaOnionBlob,
4✔
2207
                        }
4✔
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:
2✔
2231
                        l.log.Warnf("unexpected failure code received in "+
2✔
2232
                                "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
2233

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

2248
                // With the error parsed, we'll convert the into it's opaque
2249
                // form.
2250
                var b bytes.Buffer
6✔
2251
                if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
6✔
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())
6✔
2260
                if err != nil {
6✔
2261
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2262
                                "unable to handle upstream fail HTLC: %v", err)
×
2263
                        return
×
2264
                }
×
2265

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

123✔
2272
                if len(msg.Reason) < minimumFailReasonLength {
124✔
2273
                        // We've received a reason with a non-compliant length.
1✔
2274
                        // Older nodes happily relay back these failures that
1✔
2275
                        // may originate from a node further downstream.
1✔
2276
                        // Therefore we can't just fail the channel.
1✔
2277
                        //
1✔
2278
                        // We want to be compliant ourselves, so we also can't
1✔
2279
                        // pass back the reason unmodified. And we must make
1✔
2280
                        // sure that we don't hit the magic length check of 260
1✔
2281
                        // bytes in processRemoteSettleFails either.
1✔
2282
                        //
1✔
2283
                        // Because the reason is unreadable for the payer
1✔
2284
                        // anyway, we just replace it by a compliant-length
1✔
2285
                        // series of random bytes.
1✔
2286
                        msg.Reason = make([]byte, minimumFailReasonLength)
1✔
2287
                        _, err := crand.Read(msg.Reason[:])
1✔
2288
                        if err != nil {
1✔
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
123✔
2297
                err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
123✔
2298
                if err != nil {
123✔
2299
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2300
                                "unable to handle upstream fail HTLC: %v", err)
×
2301
                        return
×
2302
                }
×
2303

2304
        case *lnwire.CommitSig:
1,208✔
2305
                // Since we may have learned new preimages for the first time,
1,208✔
2306
                // we'll add them to our preimage cache. By doing this, we
1,208✔
2307
                // ensure any contested contracts watched by any on-chain
1,208✔
2308
                // arbitrators can now sweep this HTLC on-chain. We delay
1,208✔
2309
                // committing the preimages until just before accepting the new
1,208✔
2310
                // remote commitment, as afterwards the peer won't resend the
1,208✔
2311
                // Settle messages on the next channel reestablishment. Doing so
1,208✔
2312
                // allows us to more effectively batch this operation, instead
1,208✔
2313
                // of doing a single write per preimage.
1,208✔
2314
                err := l.cfg.PreimageCache.AddPreimages(
1,208✔
2315
                        l.uncommittedPreimages...,
1,208✔
2316
                )
1,208✔
2317
                if err != nil {
1,208✔
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
1,208✔
2333

1,208✔
2334
                // We just received a new updates to our local commitment
1,208✔
2335
                // chain, validate this new commitment, closing the link if
1,208✔
2336
                // invalid.
1,208✔
2337
                auxSigBlob, err := msg.CustomRecords.Serialize()
1,208✔
2338
                if err != nil {
1,208✔
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{
1,208✔
2347
                        CommitSig:  msg.CommitSig,
1,208✔
2348
                        HtlcSigs:   msg.HtlcSigs,
1,208✔
2349
                        PartialSig: msg.PartialSig,
1,208✔
2350
                        AuxSigBlob: auxSigBlob,
1,208✔
2351
                })
1,208✔
2352
                if err != nil {
1,208✔
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 :=
1,208✔
2381
                        l.channel.RevokeCurrentCommitment()
1,208✔
2382
                if err != nil {
1,208✔
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()
1,208✔
2409
                l.incomingCommitHooks.invoke()
1,208✔
2410
                l.RWMutex.Unlock()
1,208✔
2411

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

1,208✔
2414
                // Notify the incoming htlcs of which the resolutions were
1,208✔
2415
                // locked in.
1,208✔
2416
                for id, settled := range finalHTLCs {
1,542✔
2417
                        l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
334✔
2418
                                models.CircuitKey{
334✔
2419
                                        ChanID: l.ShortChanID(),
334✔
2420
                                        HtlcID: id,
334✔
2421
                                },
334✔
2422
                                channeldb.FinalHtlcInfo{
334✔
2423
                                        Settled:  settled,
334✔
2424
                                        Offchain: true,
334✔
2425
                                },
334✔
2426
                        )
334✔
2427
                }
334✔
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{
1,208✔
2433
                        HtlcKey: contractcourt.LocalHtlcSet,
1,208✔
2434
                        Htlcs:   currentHtlcs,
1,208✔
2435
                }
1,208✔
2436
                err = l.cfg.NotifyContractUpdate(newUpdate)
1,208✔
2437
                if err != nil {
1,208✔
2438
                        l.log.Errorf("unable to notify contract update: %v",
×
2439
                                err)
×
2440
                        return
×
2441
                }
×
2442

2443
                select {
1,208✔
2444
                case <-l.cg.Done():
×
2445
                        return
×
2446
                default:
1,208✔
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() {
1,870✔
2456
                        if !l.updateCommitTxOrFail(ctx) {
662✔
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) {
2,308✔
2464
                        err = l.quiescer.SendOwedStfu()
1,100✔
2465
                        if err != nil {
1,100✔
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()
1,208✔
2474
                if l.channel.IsChannelClean() {
1,408✔
2475
                        l.flushHooks.invoke()
200✔
2476
                }
200✔
2477
                l.RWMutex.Unlock()
1,208✔
2478

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

1,197✔
2484
                // We now process the message and advance our remote commit
1,197✔
2485
                // chain.
1,197✔
2486
                fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
1,197✔
2487
                if err != nil {
1,197✔
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{
1,197✔
2503
                        HtlcKey: contractcourt.RemoteHtlcSet,
1,197✔
2504
                        Htlcs:   remoteHTLCs,
1,197✔
2505
                }
1,197✔
2506
                err = l.cfg.NotifyContractUpdate(newUpdate)
1,197✔
2507
                if err != nil {
1,197✔
2508
                        l.log.Errorf("unable to notify contract update: %v",
×
2509
                                err)
×
2510
                        return
×
2511
                }
×
2512

2513
                select {
1,197✔
UNCOV
2514
                case <-l.cg.Done():
×
UNCOV
2515
                        return
×
2516
                default:
1,197✔
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 {
1,200✔
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() {
2,393✔
2545
                        l.processRemoteAdds(fwdPkg)
1,196✔
2546
                } else {
1,197✔
2547
                        l.quiescer.OnResume(func() {
1✔
2548
                                l.processRemoteAdds(fwdPkg)
×
2549
                        })
×
2550
                }
2551
                l.processRemoteSettleFails(fwdPkg)
1,197✔
2552

1,197✔
2553
                // If the link failed during processing the adds, we must
1,197✔
2554
                // return to ensure we won't attempted to update the state
1,197✔
2555
                // further.
1,197✔
2556
                if l.failed {
1,197✔
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() {
1,521✔
2568
                        if !l.updateCommitTxOrFail(ctx) {
330✔
2569
                                return
6✔
2570
                        }
6✔
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()
1,191✔
2576
                if l.channel.IsChannelClean() {
1,355✔
2577
                        l.flushHooks.invoke()
164✔
2578
                }
164✔
2579
                l.RWMutex.Unlock()
1,191✔
2580

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

3✔
2586
                isDust, err := l.exceedsFeeExposureLimit(fee)
3✔
2587
                if err != nil {
3✔
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 {
3✔
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 {
3✔
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)
3✔
2616

2617
        case *lnwire.Stfu:
5✔
2618
                err := l.handleStfu(msg)
5✔
2619
                if err != nil {
5✔
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:
1✔
2627
                l.log.Warnf("received warning message from peer: %v",
1✔
2628
                        msg.Warning())
1✔
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 {
5✔
2658
        if !l.noDanglingUpdates(lntypes.Remote) {
5✔
2659
                return ErrPendingRemoteUpdates
×
2660
        }
×
2661
        err := l.quiescer.RecvStfu(*stfu)
5✔
2662
        if err != nil {
5✔
2663
                return err
×
2664
        }
×
2665

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

2671
        return nil
1✔
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 {
1,213✔
2689
        pendingOnLocal := l.channel.NumPendingUpdates(
1,213✔
2690
                whose, lntypes.Local,
1,213✔
2691
        )
1,213✔
2692
        pendingOnRemote := l.channel.NumPendingUpdates(
1,213✔
2693
                whose, lntypes.Remote,
1,213✔
2694
        )
1,213✔
2695

1,213✔
2696
        return pendingOnLocal == 0 && pendingOnRemote == 0
1,213✔
2697
}
1,213✔
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 {
1,387✔
2706
        // First, remove the downstream Add packets that were included in the
1,387✔
2707
        // previous commitment signature. This will prevent the Adds from being
1,387✔
2708
        // replayed if this link disconnects.
1,387✔
2709
        for _, inKey := range l.openedCircuits {
1,854✔
2710
                // In order to test the sphinx replay logic of the remote
467✔
2711
                // party, unsafe replay does not acknowledge the packets from
467✔
2712
                // the mailbox. We can then force a replay of any Add packets
467✔
2713
                // held in memory by disconnecting and reconnecting the link.
467✔
2714
                if l.cfg.UnsafeReplay {
470✔
2715
                        continue
3✔
2716
                }
2717

2718
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
467✔
2719
                l.mailBox.AckPacket(inKey)
467✔
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...)
1,387✔
2727
        switch err {
1,387✔
2728
        case nil:
1,387✔
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 {
1,429✔
2743
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
42✔
2744
                        inKey)
42✔
2745
                l.mailBox.AckPacket(inKey)
42✔
2746
        }
42✔
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]
1,387✔
2751
        l.closedCircuits = l.closedCircuits[:0]
1,387✔
2752

1,387✔
2753
        return nil
1,387✔
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 {
1,237✔
2759
        err := l.updateCommitTx(ctx)
1,237✔
2760
        switch err {
1,237✔
2761
        // No error encountered, success.
2762
        case nil:
1,228✔
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:
9✔
2774
                l.failf(LinkFailureError{code: ErrInternalError},
9✔
2775
                        "unable to update commitment: %v", err)
9✔
2776
                return false
9✔
2777
        }
2778

2779
        return true
1,228✔
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 {
1,295✔
2786
        // Preemptively write all pending keystones to disk, just in case the
1,295✔
2787
        // HTLCs we have in memory are included in the subsequent attempt to
1,295✔
2788
        // sign a commitment state.
1,295✔
2789
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
1,295✔
2790
        if err != nil {
1,295✔
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]
1,295✔
2798

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

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

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

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

77✔
2822
                return nil
77✔
2823
        } else if err != nil {
1,294✔
2824
                return err
×
2825
        }
×
2826

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

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

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

2847
        select {
1,217✔
2848
        case <-l.cg.Done():
10✔
2849
                return ErrLinkShuttingDown
10✔
2850
        default:
1,207✔
2851
        }
2852

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

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

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

1,207✔
2873
        return nil
1,207✔
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 {
444✔
2881
        return l.cfg.Peer.PubKey()
444✔
2882
}
444✔
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 {
855✔
2887
        return l.channel.ChannelPoint()
855✔
2888
}
855✔
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 {
4,252✔
2896
        l.RLock()
4,252✔
2897
        defer l.RUnlock()
4,252✔
2898

4,252✔
2899
        return l.channel.ShortChanID()
4,252✔
2900
}
4,252✔
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,946✔
2929
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
3,946✔
2930
}
3,946✔
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 {
814✔
2939
        // Get the balance available on the channel for new HTLCs. This takes
814✔
2940
        // the channel reserve into account so HTLCs up to this value won't
814✔
2941
        // violate it.
814✔
2942
        return l.channel.AvailableBalance()
814✔
2943
}
814✔
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 {
2,526✔
2959

2,526✔
2960
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
2,526✔
2961
}
2,526✔
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 {
672✔
2968
        return l.channel.CommitFeeRate()
672✔
2969
}
672✔
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 {
1,602✔
2976
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
1,602✔
2977
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
1,602✔
2978
        chanType := l.channel.State().ChanType
1,602✔
2979

1,602✔
2980
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
1,602✔
2981
}
1,602✔
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 {
1,890✔
2989
        if remote {
2,850✔
2990
                return l.channel.State().RemoteCommitment.CommitFee
960✔
2991
        }
960✔
2992

2993
        return l.channel.State().LocalCommitment.CommitFee
933✔
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) {
6✔
3009

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

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

6✔
3017
        // Calculate the local and remote commitment fees using this dry-run
6✔
3018
        // fee.
6✔
3019
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
3020
        if err != nil {
6✔
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)
6✔
3027
        if totalLocalDust > l.cfg.MaxFeeExposure {
6✔
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(
6✔
3036
                remoteFee,
6✔
3037
        )
6✔
3038

6✔
3039
        if totalRemoteDust > l.cfg.MaxFeeExposure {
6✔
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
6✔
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 {
933✔
3060

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

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

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

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

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

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

933✔
3082
        if l.getCommitFee(true) > commitFee {
962✔
3083
                commitFee = l.getCommitFee(true)
29✔
3084
        }
29✔
3085

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

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

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

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

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

4✔
3113
                return true
4✔
3114
        }
4✔
3115

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

3126
        if remoteDustSum > l.cfg.MaxFeeExposure {
929✔
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
929✔
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 {
1,802✔
3149

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

9,761✔
3153
                var dustLimit btcutil.Amount
9,761✔
3154
                if whoseCommit.IsLocal() {
14,643✔
3155
                        dustLimit = localDustLimit
4,882✔
3156
                } else {
9,764✔
3157
                        dustLimit = remoteDustLimit
4,882✔
3158
                }
4,882✔
3159

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

3166
        return isDust
1,802✔
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 {
6✔
3174
        return l.channel.State().ZeroConfConfirmed()
6✔
3175
}
6✔
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 {
6✔
3182
        return l.channel.State().ZeroConfRealScid()
6✔
3183
}
6✔
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 {
216✔
3190
        return l.channel.State().IsZeroConf()
216✔
3191
}
216✔
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 {
377✔
3200
        return l.channel.State().NegotiatedAliasFeature()
377✔
3201
}
377✔
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 {
222✔
3207
        return l.cfg.GetAliases(l.ShortChanID())
222✔
3208
}
222✔
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) {
217✔
3215

217✔
3216
        l.Lock()
217✔
3217
        l.cfg.FailAliasUpdate = closure
217✔
3218
        l.Unlock()
217✔
3219
}
217✔
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) {
216✔
3225
        l.Lock()
216✔
3226
        l.mailBox = mailbox
216✔
3227
        l.upstream = mailbox.MessageOutBox()
216✔
3228
        l.downstream = mailbox.PacketOutBox()
216✔
3229
        l.Unlock()
216✔
3230

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

216✔
3235
        // Also set the mailbox's dust closure so that it can query whether HTLC's
216✔
3236
        // are dust given the current feerate.
216✔
3237
        l.mailBox.SetDustClosure(l.getDustClosure())
216✔
3238
}
216✔
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) {
15✔
3249

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

15✔
3253
        l.cfg.FwrdingPolicy = newPolicy
15✔
3254
}
15✔
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 {
52✔
3268

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

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

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

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

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

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

3313
        // Check whether the outgoing htlc satisfies the channel policy.
3314
        err := l.canSendHtlc(
46✔
3315
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
46✔
3316
                originalScid, customRecords,
46✔
3317
        )
46✔
3318
        if err != nil {
62✔
3319
                return err
16✔
3320
        }
16✔
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
33✔
3327
        if incomingTimeout < outgoingTimeout+timeDelta {
35✔
3328
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
2✔
3329
                        "expected at least %v block delta, got %v block delta",
2✔
3330
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
2✔
3331

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

3343
        return nil
31✔
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 {
409✔
3354

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

409✔
3359
        // We pass in hop.Source here as this is only used in the Switch when
409✔
3360
        // trying to send over a local link. This causes the fallback mechanism
409✔
3361
        // to occur.
409✔
3362
        return l.canSendHtlc(
409✔
3363
                policy, payHash, amt, timeout, heightNow, hop.Source,
409✔
3364
                customRecords,
409✔
3365
        )
409✔
3366
}
409✔
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 {
452✔
3374

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

11✔
3383
                // As part of the returned error, we'll send our latest routing
11✔
3384
                // policy so the sending node obtains the most up to date data.
11✔
3385
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
22✔
3386
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
11✔
3387
                }
11✔
3388
                failure := l.createFailureWithUpdate(false, originalScid, cb)
11✔
3389
                return NewLinkError(failure)
11✔
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 {
450✔
3395
                l.log.Warnf("outgoing htlc(%x) is too large: max_htlc=%v, "+
6✔
3396
                        "htlc_value=%v", payHash[:], policy.MaxHTLC, amt)
6✔
3397

6✔
3398
                // As part of the returned error, we'll send our latest routing
6✔
3399
                // policy so the sending node obtains the most up-to-date data.
6✔
3400
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
12✔
3401
                        return lnwire.NewTemporaryChannelFailure(upd)
6✔
3402
                }
6✔
3403
                failure := l.createFailureWithUpdate(false, originalScid, cb)
6✔
3404
                return NewDetailedLinkError(failure, OutgoingFailureHTLCExceedsMax)
6✔
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 {
443✔
3411
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
2✔
3412
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
2✔
3413
                        timeout, heightNow)
2✔
3414

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

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

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

3431
        // We now check the available bandwidth to see if this HTLC can be
3432
        // forwarded.
3433
        availableBandwidth := l.Bandwidth()
438✔
3434
        auxBandwidth, err := fn.MapOptionZ(
438✔
3435
                l.cfg.AuxTrafficShaper,
438✔
3436
                func(ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
438✔
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 {
438✔
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() {
438✔
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 {
442✔
3467
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
4✔
3468
                        "larger than %v", amt, availableBandwidth)
4✔
3469
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
3470
                        return lnwire.NewTemporaryChannelFailure(upd)
4✔
3471
                }
4✔
3472
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
3473
                return NewDetailedLinkError(
4✔
3474
                        failure, OutgoingFailureInsufficientBalance,
4✔
3475
                )
4✔
3476
        }
3477

3478
        return nil
437✔
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) {
7✔
3539
        snapshot := l.channel.StateSnapshot()
7✔
3540

7✔
3541
        return snapshot.ChannelCommitment.CommitHeight,
7✔
3542
                snapshot.TotalMSatSent,
7✔
3543
                snapshot.TotalMSatReceived
7✔
3544
}
7✔
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 {
482✔
3559
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
482✔
3560
                pkt.inKey(), pkt.outKey())
482✔
3561

482✔
3562
        return l.mailBox.AddPacket(pkt)
482✔
3563
}
482✔
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,378✔
3570
        select {
3,378✔
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,378✔
3577
        }
3578

3579
        err := l.mailBox.AddMessage(message)
3,378✔
3580
        if err != nil {
3,378✔
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 {
3✔
3589

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

3✔
3592
        // We skip sending the UpdateFee message if the channel is not
3✔
3593
        // currently eligible to forward messages.
3✔
3594
        if !l.eligibleToUpdate() {
3✔
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)
3✔
3602
        if err != nil {
3✔
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 {
3✔
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 {
3✔
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)
3✔
3620

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

3628
        return l.updateCommitTx(ctx)
3✔
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) {
1,197✔
3637
        if len(fwdPkg.SettleFails) == 0 {
2,078✔
3638
                l.log.Trace("fwd package has no settle/fails to process " +
881✔
3639
                        "exiting early")
881✔
3640

881✔
3641
                return
881✔
3642
        }
881✔
3643

3644
        // Exit early if the fwdPkg is already processed.
3645
        if fwdPkg.State == channeldb.FwdStateCompleted {
319✔
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)
319✔
3652

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

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

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

3667
                switch msg := update.UpdateMsg.(type) {
319✔
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:
196✔
3672
                        // If hodl.SettleIncoming is requested, we will not
196✔
3673
                        // forward the SETTLE to the switch and will not signal
196✔
3674
                        // a free slot on the commitment transaction.
196✔
3675
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
196✔
3676
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
3677
                                continue
×
3678
                        }
3679

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

196✔
3687
                        // Add the packet to the batch to be forwarded, and
196✔
3688
                        // notify the overflow queue that a spare spot has been
196✔
3689
                        // freed up within the commitment state.
196✔
3690
                        switchPackets = append(switchPackets, settlePacket)
196✔
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:
126✔
3697
                        // If hodl.SettleIncoming is requested, we will not
126✔
3698
                        // forward the FAIL to the switch and will not signal a
126✔
3699
                        // free slot on the commitment transaction.
126✔
3700
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
126✔
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{
126✔
3710
                                outgoingChanID: l.ShortChanID(),
126✔
3711
                                outgoingHTLCID: msg.ID,
126✔
3712
                                destRef:        &destRef,
126✔
3713
                                htlc:           msg,
126✔
3714
                        }
126✔
3715

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

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

3737
        // Only spawn the task forward packets we have a non-zero number.
3738
        if len(switchPackets) > 0 {
638✔
3739
                go l.forwardBatch(false, switchPackets...)
319✔
3740
        }
319✔
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) {
1,199✔
3752
        // Exit early if there are no adds to process.
1,199✔
3753
        if len(fwdPkg.Adds) == 0 {
2,081✔
3754
                l.log.Trace("fwd package has no adds to process exiting early")
882✔
3755

882✔
3756
                return
882✔
3757
        }
882✔
3758

3759
        // Exit early if the fwdPkg is already processed.
3760
        if fwdPkg.State == channeldb.FwdStateCompleted {
320✔
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",
320✔
3767
                len(fwdPkg.Adds), fwdPkg.Height)
320✔
3768

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

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

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

×
3786
                        continue
×
3787
                }
3788

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

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

452✔
3804
                        decodeReqs = append(decodeReqs, req)
452✔
3805
                        unackedAdds = append(unackedAdds, msg)
452✔
3806
                }
452✔
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
320✔
3812

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

3826
        var switchPackets []*htlcPacket
320✔
3827

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

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

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

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

5✔
3855
                        continue
5✔
3856
                }
3857

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

450✔
3860
                pld, routeRole, pldErr := chanIterator.HopPayload()
450✔
3861
                if pldErr != nil {
453✔
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(
450✔
3924
                        l.cfg.ExtractErrorEncrypter,
450✔
3925
                        routeRole == hop.RouteRoleIntroduction,
450✔
3926
                )
450✔
3927
                if failureCode != lnwire.CodeNone {
451✔
3928
                        // If we're unable to process the onion blob than we
1✔
3929
                        // should send the malformed htlc error to payment
1✔
3930
                        // sender.
1✔
3931
                        l.sendMalformedHTLCError(
1✔
3932
                                add.ID, failureCode, add.OnionBlob,
1✔
3933
                                &sourceRef,
1✔
3934
                        )
1✔
3935

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

1✔
3939
                        continue
1✔
3940
                }
3941

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

449✔
3944
                // Check whether the payload we've just processed uses our
449✔
3945
                // node as the introduction point (gave us a blinding key in
449✔
3946
                // the payload itself) and fail it back if we don't support
449✔
3947
                // route blinding.
449✔
3948
                if fwdInfo.NextBlinding.IsSome() &&
449✔
3949
                        l.cfg.DisallowRouteBlinding {
452✔
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 {
449✔
3968
                case hop.Exit:
413✔
3969
                        err := l.processExitHop(
413✔
3970
                                add, sourceRef, obfuscator, fwdInfo,
413✔
3971
                                heightNow, pld,
413✔
3972
                        )
413✔
3973
                        if err != nil {
413✔
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:
39✔
3984
                        // If hodl.AddIncoming is requested, we will not
39✔
3985
                        // validate the forwarded ADD, nor will we send the
39✔
3986
                        // packet to the htlc switch.
39✔
3987
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
39✔
3988
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3989
                                continue
×
3990
                        }
3991

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

39✔
3999
                        switch fwdPkg.State {
39✔
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{
39✔
4072
                                Expiry:        fwdInfo.OutgoingCTLV,
39✔
4073
                                Amount:        fwdInfo.AmountToForward,
39✔
4074
                                PaymentHash:   add.PaymentHash,
39✔
4075
                                BlindingPoint: fwdInfo.NextBlinding,
39✔
4076
                        }
39✔
4077

39✔
4078
                        endorseValue.WhenSome(func(e byte) {
78✔
4079
                                addMsg.CustomRecords = map[uint64][]byte{
39✔
4080
                                        endorseType: {e},
39✔
4081
                                }
39✔
4082
                        })
39✔
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])
39✔
4088
                        err := chanIterator.EncodeNextHop(buf)
39✔
4089
                        if err != nil {
39✔
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 {
78✔
4117
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
39✔
4118

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

39✔
4136
                                fwdPkg.FwdFilter.Set(idx)
39✔
4137
                                switchPackets = append(switchPackets,
39✔
4138
                                        updatePacket)
39✔
4139
                        }
39✔
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 {
637✔
4146
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
317✔
4147
                if err != nil {
317✔
4148
                        l.failf(LinkFailureError{code: ErrInternalError},
×
4149
                                "unable to set fwd filter: %v", err)
×
4150
                        return
×
4151
                }
×
4152
        }
4153

4154
        if len(switchPackets) == 0 {
604✔
4155
                return
284✔
4156
        }
284✔
4157

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

39✔
4161
        // NOTE: This call is made synchronous so that we ensure all circuits
39✔
4162
        // are committed in the exact order that they are processed in the link.
39✔
4163
        // Failing to do this could cause reorderings/gaps in the range of
39✔
4164
        // opened circuits, which violates assumptions made by the circuit
39✔
4165
        // trimming.
39✔
4166
        l.forwardBatch(reforward, switchPackets...)
39✔
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] {
39✔
4174

39✔
4175
        // Only relay experimental signal if we are within the experiment
39✔
4176
        // period.
39✔
4177
        if !l.cfg.ShouldFwdExpEndorsement() {
42✔
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 {
78✔
4184
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
39✔
4185
        }
39✔
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 {
413✔
4215

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

110✔
4223
                return nil
110✔
4224
        }
110✔
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(
306✔
4229
                l.cfg.AuxTrafficShaper,
306✔
4230
                func(ts AuxTrafficShaper) bool {
306✔
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 {
406✔
4240
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
100✔
4241
                        "incompatible value: expected <=%v, got %v",
100✔
4242
                        add.PaymentHash, add.Amount, fwdInfo.AmountToForward)
100✔
4243

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

100✔
4249
                return nil
100✔
4250
        }
100✔
4251

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

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

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

1✔
4265
                return nil
1✔
4266
        }
1✔
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)
205✔
4272

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

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

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

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

4300
        // Process the received resolution.
4301
        return l.processHtlcResolution(event, htlc)
149✔
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 {
200✔
4307

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

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

200✔
4312
        err := l.channel.SettleHTLC(
200✔
4313
                preimage, htlcIndex, &sourceRef, nil, nil,
200✔
4314
        )
200✔
4315
        if err != nil {
200✔
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) {
203✔
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{
200✔
4330
                ChanID:          l.ChanID(),
200✔
4331
                ID:              htlcIndex,
200✔
4332
                PaymentPreimage: preimage,
200✔
4333
        })
200✔
4334

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

200✔
4347
        return nil
200✔
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) {
580✔
4354
        // Don't forward packets for which we already have a response in our
580✔
4355
        // mailbox. This could happen if a packet fails and is buffered in the
580✔
4356
        // mailbox, and the incoming link flaps.
580✔
4357
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
580✔
4358
        for _, pkt := range packets {
1,160✔
4359
                if l.mailBox.HasPacket(pkt.inKey()) {
583✔
4360
                        continue
3✔
4361
                }
4362

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

4366
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
580✔
4367
        if err != nil {
591✔
4368
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
4369
                        "settle/fail over htlcswitch: %v", err)
11✔
4370
        }
11✔
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) {
108✔
4378

108✔
4379
        reason, err := e.EncryptFirstHop(failure.WireMessage())
108✔
4380
        if err != nil {
108✔
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)
108✔
4386
        if err != nil {
108✔
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(
108✔
4394
                add.ID, e, reason,
108✔
4395
        ); err != nil {
108✔
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
108✔
4404
        if isReceive {
216✔
4405
                eventType = HtlcEventTypeReceive
108✔
4406
        } else {
111✔
4407
                eventType = HtlcEventTypeForward
3✔
4408
        }
3✔
4409

4410
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
108✔
4411
                HtlcKey{
108✔
4412
                        IncomingCircuit: models.CircuitKey{
108✔
4413
                                ChanID: l.ShortChanID(),
108✔
4414
                                HtlcID: add.ID,
108✔
4415
                        },
108✔
4416
                },
108✔
4417
                HtlcInfo{
108✔
4418
                        IncomingTimeLock: add.Expiry,
108✔
4419
                        IncomingAmt:      add.Amount,
108✔
4420
                },
108✔
4421
                eventType,
108✔
4422
                failure,
108✔
4423
                true,
108✔
4424
        )
108✔
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 {
124✔
4440

124✔
4441
        var msg lnwire.Message
124✔
4442
        switch {
124✔
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():
124✔
4464
                msg = &lnwire.UpdateFailHTLC{
124✔
4465
                        ChanID: l.ChanID(),
124✔
4466
                        ID:     htlcIndex,
124✔
4467
                        Reason: originalFailure,
124✔
4468
                }
124✔
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 {
124✔
4509
                l.log.Warnf("Send update fail failed: %v", err)
×
4510
        }
×
4511

4512
        return nil
124✔
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) {
6✔
4520

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

4528
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
6✔
4529
                ChanID:       l.ChanID(),
6✔
4530
                ID:           htlcIndex,
6✔
4531
                ShaOnionBlob: shaOnionBlob,
6✔
4532
                FailureCode:  code,
6✔
4533
        })
6✔
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{}) {
17✔
4543

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

17✔
4546
        // Return if we have already notified about a failure.
17✔
4547
        if l.failed {
20✔
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)
17✔
4554

17✔
4555
        // Set failed, such that we won't process any more updates, and notify
17✔
4556
        // the peer about the failure.
17✔
4557
        l.failed = true
17✔
4558
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
17✔
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