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

lightningnetwork / lnd / 18197857992

02 Oct 2025 03:32PM UTC coverage: 66.622% (-0.02%) from 66.646%
18197857992

Pull #10267

github

web-flow
Merge 0d9bfccfe into 1c2ff4a7e
Pull Request #10267: [g175] multi: small G175 preparations

24 of 141 new or added lines in 12 files covered. (17.02%)

64 existing lines in 20 files now uncovered.

137216 of 205963 relevant lines covered (66.62%)

21302.01 hits per line

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

77.2
/htlcswitch/link.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

301
        // AuxChannelNegotiator is an optional interface that allows aux channel
302
        // implementations to inject and process custom records over channel
303
        // related wire messages.
304
        AuxChannelNegotiator fn.Option[lnwallet.AuxChannelNegotiator]
305

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

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

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

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

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

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

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

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

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

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

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

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

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

380
        sync.RWMutex
381

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5✔
465
        return hookID
5✔
466
}
467

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

216✔
613
        return nil
216✔
614
}
615

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

795
        return out
4✔
796
}
797

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

894
        return cb(update)
25✔
895
}
896

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

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

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

919
        var msgsToReSend []lnwire.Message
173✔
920

173✔
921
        // Next, we'll wait indefinitely to receive the ChanSync message. The
173✔
922
        // first message sent MUST be the ChanSync message.
173✔
923
        select {
173✔
924
        case msg := <-l.upstream:
173✔
925
                l.log.Tracef("Received msg=%v from peer(%x)", msg.MsgType(),
173✔
926
                        l.cfg.Peer.PubKey())
173✔
927

173✔
928
                remoteChanSyncMsg, ok := msg.(*lnwire.ChannelReestablish)
173✔
929
                if !ok {
173✔
930
                        return fmt.Errorf("first message sent to sync "+
×
931
                                "should be ChannelReestablish, instead "+
×
932
                                "received: %T", msg)
×
933
                }
×
934

935
                // If the remote party indicates that they think we haven't
936
                // done any state updates yet, then we'll retransmit the
937
                // channel_ready message first. We do this, as at this point
938
                // we can't be sure if they've really received the
939
                // ChannelReady message.
940
                if remoteChanSyncMsg.NextLocalCommitHeight == 1 &&
173✔
941
                        localChanSyncMsg.NextLocalCommitHeight == 1 &&
173✔
942
                        !l.channel.IsPending() {
340✔
943

167✔
944
                        l.log.Infof("resending ChannelReady message to peer")
167✔
945

167✔
946
                        nextRevocation, err := l.channel.NextRevocationKey()
167✔
947
                        if err != nil {
167✔
948
                                return fmt.Errorf("unable to create next "+
×
949
                                        "revocation: %v", err)
×
950
                        }
×
951

952
                        channelReadyMsg := lnwire.NewChannelReady(
167✔
953
                                l.ChanID(), nextRevocation,
167✔
954
                        )
167✔
955

167✔
956
                        // If this is a taproot channel, then we'll send the
167✔
957
                        // very same nonce that we sent above, as they should
167✔
958
                        // take the latest verification nonce we send.
167✔
959
                        if chanState.ChanType.IsTaproot() {
170✔
960
                                //nolint:ll
3✔
961
                                channelReadyMsg.NextLocalNonce = localChanSyncMsg.LocalNonce
3✔
962
                        }
3✔
963

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

979
                                // getAliases returns a copy of the alias slice
980
                                // so it is ok to use a pointer to the first
981
                                // entry.
982
                                channelReadyMsg.AliasScid = &aliases[0]
3✔
983
                        }
984

985
                        err = l.cfg.Peer.SendMessage(false, channelReadyMsg)
167✔
986
                        if err != nil {
167✔
987
                                return fmt.Errorf("unable to re-send "+
×
988
                                        "ChannelReady: %v", err)
×
989
                        }
×
990
                }
991

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

173✔
995
                // If we have an AuxChannelNegotiator we notify any external
173✔
996
                // component for this message. This serves as a notification
173✔
997
                // that the reestablish message was received.
173✔
998
                l.cfg.AuxChannelNegotiator.WhenSome(
173✔
999
                        func(acn lnwallet.AuxChannelNegotiator) {
173✔
1000
                                fundingPoint := l.channel.ChannelPoint()
×
1001
                                cid := lnwire.NewChanIDFromOutPoint(
×
1002
                                        fundingPoint,
×
1003
                                )
×
1004

×
1005
                                acn.ProcessReestablish(
×
1006
                                        cid, l.cfg.Peer.PubKey(),
×
1007
                                )
×
1008
                        },
×
1009
                )
1010

1011
                var (
173✔
1012
                        openedCircuits []CircuitKey
173✔
1013
                        closedCircuits []CircuitKey
173✔
1014
                )
173✔
1015

173✔
1016
                // We've just received a ChanSync message from the remote
173✔
1017
                // party, so we'll process the message  in order to determine
173✔
1018
                // if we need to re-transmit any messages to the remote party.
173✔
1019
                ctx, cancel := l.cg.Create(ctx)
173✔
1020
                defer cancel()
173✔
1021
                msgsToReSend, openedCircuits, closedCircuits, err =
173✔
1022
                        l.channel.ProcessChanSyncMsg(ctx, remoteChanSyncMsg)
173✔
1023
                if err != nil {
176✔
1024
                        return err
3✔
1025
                }
3✔
1026

1027
                // Repopulate any identifiers for circuits that may have been
1028
                // opened or unclosed. This may happen if we needed to
1029
                // retransmit a commitment signature message.
1030
                l.openedCircuits = openedCircuits
173✔
1031
                l.closedCircuits = closedCircuits
173✔
1032

173✔
1033
                // Ensure that all packets have been have been removed from the
173✔
1034
                // link's mailbox.
173✔
1035
                if err := l.ackDownStreamPackets(); err != nil {
173✔
1036
                        return err
×
1037
                }
×
1038

1039
                if len(msgsToReSend) > 0 {
178✔
1040
                        l.log.Infof("sending %v updates to synchronize the "+
5✔
1041
                                "state", len(msgsToReSend))
5✔
1042
                }
5✔
1043

1044
                // If we have any messages to retransmit, we'll do so
1045
                // immediately so we return to a synchronized state as soon as
1046
                // possible.
1047
                for _, msg := range msgsToReSend {
184✔
1048
                        err := l.cfg.Peer.SendMessage(false, msg)
11✔
1049
                        if err != nil {
11✔
1050
                                l.log.Errorf("failed to send %v: %v",
×
1051
                                        msg.MsgType(), err)
×
1052
                        }
×
1053
                }
1054

1055
        case <-l.cg.Done():
3✔
1056
                return ErrLinkShuttingDown
3✔
1057
        }
1058

1059
        return nil
173✔
1060
}
1061

1062
// resolveFwdPkgs loads any forwarding packages for this link from disk, and
1063
// reprocesses them in order. The primary goal is to make sure that any HTLCs
1064
// we previously received are reinstated in memory, and forwarded to the switch
1065
// if necessary. After a restart, this will also delete any previously
1066
// completed packages.
1067
func (l *channelLink) resolveFwdPkgs(ctx context.Context) error {
216✔
1068
        fwdPkgs, err := l.channel.LoadFwdPkgs()
216✔
1069
        if err != nil {
217✔
1070
                return err
1✔
1071
        }
1✔
1072

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

215✔
1075
        for _, fwdPkg := range fwdPkgs {
224✔
1076
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
9✔
UNCOV
1077
                        return err
×
UNCOV
1078
                }
×
1079
        }
1080

1081
        // If any of our reprocessing steps require an update to the commitment
1082
        // txn, we initiate a state transition to capture all relevant changes.
1083
        if l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote) > 0 {
218✔
1084
                return l.updateCommitTx(ctx)
3✔
1085
        }
3✔
1086

1087
        return nil
215✔
1088
}
1089

1090
// resolveFwdPkg interprets the FwdState of the provided package, either
1091
// reprocesses any outstanding htlcs in the package, or performs garbage
1092
// collection on the package.
1093
func (l *channelLink) resolveFwdPkg(fwdPkg *channeldb.FwdPkg) error {
9✔
1094
        // Remove any completed packages to clear up space.
9✔
1095
        if fwdPkg.State == channeldb.FwdStateCompleted {
13✔
1096
                l.log.Debugf("removing completed fwd pkg for height=%d",
4✔
1097
                        fwdPkg.Height)
4✔
1098

4✔
1099
                err := l.channel.RemoveFwdPkgs(fwdPkg.Height)
4✔
1100
                if err != nil {
4✔
UNCOV
1101
                        l.log.Errorf("unable to remove fwd pkg for height=%d: "+
×
UNCOV
1102
                                "%v", fwdPkg.Height, err)
×
UNCOV
1103
                        return err
×
UNCOV
1104
                }
×
1105
        }
1106

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

1113
        // If the package is fully acked but not completed, it must still have
1114
        // settles and fails to propagate.
1115
        if !fwdPkg.SettleFailFilter.IsFull() {
12✔
1116
                l.processRemoteSettleFails(fwdPkg)
3✔
1117
        }
3✔
1118

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

6✔
1126
                // If the link failed during processing the adds, we must
6✔
1127
                // return to ensure we won't attempted to update the state
6✔
1128
                // further.
6✔
1129
                if l.failed {
6✔
1130
                        return fmt.Errorf("link failed while " +
×
1131
                                "processing remote adds")
×
1132
                }
×
1133
        }
1134

1135
        return nil
9✔
1136
}
1137

1138
// fwdPkgGarbager periodically reads all forwarding packages from disk and
1139
// removes those that can be discarded. It is safe to do this entirely in the
1140
// background, since all state is coordinated on disk. This also ensures the
1141
// link can continue to process messages and interleave database accesses.
1142
//
1143
// NOTE: This MUST be run as a goroutine.
1144
func (l *channelLink) fwdPkgGarbager() {
215✔
1145
        defer l.cg.WgDone()
215✔
1146

215✔
1147
        l.cfg.FwdPkgGCTicker.Resume()
215✔
1148
        defer l.cfg.FwdPkgGCTicker.Stop()
215✔
1149

215✔
1150
        if err := l.loadAndRemove(); err != nil {
215✔
1151
                l.log.Warnf("unable to run initial fwd pkgs gc: %v", err)
×
1152
        }
×
1153

1154
        for {
450✔
1155
                select {
235✔
1156
                case <-l.cfg.FwdPkgGCTicker.Ticks():
20✔
1157
                        if err := l.loadAndRemove(); err != nil {
40✔
1158
                                l.log.Warnf("unable to remove fwd pkgs: %v",
20✔
1159
                                        err)
20✔
1160
                                continue
20✔
1161
                        }
1162
                case <-l.cg.Done():
205✔
1163
                        return
205✔
1164
                }
1165
        }
1166
}
1167

1168
// loadAndRemove loads all the channels forwarding packages and determines if
1169
// they can be removed. It is called once before the FwdPkgGCTicker ticks so that
1170
// a longer tick interval can be used.
1171
func (l *channelLink) loadAndRemove() error {
235✔
1172
        fwdPkgs, err := l.channel.LoadFwdPkgs()
235✔
1173
        if err != nil {
255✔
1174
                return err
20✔
1175
        }
20✔
1176

1177
        var removeHeights []uint64
215✔
1178
        for _, fwdPkg := range fwdPkgs {
223✔
1179
                if fwdPkg.State != channeldb.FwdStateCompleted {
16✔
1180
                        continue
8✔
1181
                }
1182

1183
                removeHeights = append(removeHeights, fwdPkg.Height)
3✔
1184
        }
1185

1186
        // If removeHeights is empty, return early so we don't use a db
1187
        // transaction.
1188
        if len(removeHeights) == 0 {
430✔
1189
                return nil
215✔
1190
        }
215✔
1191

1192
        return l.channel.RemoveFwdPkgs(removeHeights...)
3✔
1193
}
1194

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

3✔
1200
        var errDataLoss *lnwallet.ErrCommitSyncLocalDataLoss
3✔
1201

3✔
1202
        switch {
3✔
1203
        case errors.Is(err, ErrLinkShuttingDown):
3✔
1204
                l.log.Debugf("unable to sync channel states, link is " +
3✔
1205
                        "shutting down")
3✔
1206
                return
3✔
1207

1208
        // We failed syncing the commit chains, probably because the remote has
1209
        // lost state. We should force close the channel.
1210
        case errors.Is(err, lnwallet.ErrCommitSyncRemoteDataLoss):
3✔
1211
                fallthrough
3✔
1212

1213
        // The remote sent us an invalid last commit secret, we should force
1214
        // close the channel.
1215
        // TODO(halseth): and permanently ban the peer?
1216
        case errors.Is(err, lnwallet.ErrInvalidLastCommitSecret):
3✔
1217
                fallthrough
3✔
1218

1219
        // The remote sent us a commit point different from what they sent us
1220
        // before.
1221
        // TODO(halseth): ban peer?
1222
        case errors.Is(err, lnwallet.ErrInvalidLocalUnrevokedCommitPoint):
3✔
1223
                // We'll fail the link and tell the peer to force close the
3✔
1224
                // channel. Note that the database state is not updated here,
3✔
1225
                // but will be updated when the close transaction is ready to
3✔
1226
                // avoid that we go down before storing the transaction in the
3✔
1227
                // db.
3✔
1228
                l.failf(
3✔
1229
                        LinkFailureError{
3✔
1230
                                code:          ErrSyncError,
3✔
1231
                                FailureAction: LinkFailureForceClose,
3✔
1232
                        },
3✔
1233
                        "unable to synchronize channel states: %v", err,
3✔
1234
                )
3✔
1235

1236
        // We have lost state and cannot safely force close the channel. Fail
1237
        // the channel and wait for the remote to hopefully force close it. The
1238
        // remote has sent us its latest unrevoked commitment point, and we'll
1239
        // store it in the database, such that we can attempt to recover the
1240
        // funds if the remote force closes the channel.
1241
        case errors.As(err, &errDataLoss):
3✔
1242
                err := l.channel.MarkDataLoss(
3✔
1243
                        errDataLoss.CommitPoint,
3✔
1244
                )
3✔
1245
                if err != nil {
3✔
1246
                        l.log.Errorf("unable to mark channel data loss: %v",
×
1247
                                err)
×
1248
                }
×
1249

1250
        // We determined the commit chains were not possible to sync. We
1251
        // cautiously fail the channel, but don't force close.
1252
        // TODO(halseth): can we safely force close in any cases where this
1253
        // error is returned?
1254
        case errors.Is(err, lnwallet.ErrCannotSyncCommitChains):
×
1255
                if err := l.channel.MarkBorked(); err != nil {
×
1256
                        l.log.Errorf("unable to mark channel borked: %v", err)
×
1257
                }
×
1258

1259
        // Other, unspecified error.
1260
        default:
×
1261
        }
1262

1263
        l.failf(
3✔
1264
                LinkFailureError{
3✔
1265
                        code:          ErrRecoveryError,
3✔
1266
                        FailureAction: LinkFailureForceNone,
3✔
1267
                },
3✔
1268
                "unable to synchronize channel states: %v", err,
3✔
1269
        )
3✔
1270
}
1271

1272
// htlcManager is the primary goroutine which drives a channel's commitment
1273
// update state-machine in response to messages received via several channels.
1274
// This goroutine reads messages from the upstream (remote) peer, and also from
1275
// downstream channel managed by the channel link. In the event that an htlc
1276
// needs to be forwarded, then send-only forward handler is used which sends
1277
// htlc packets to the switch. Additionally, this goroutine handles acting upon
1278
// all timeouts for any active HTLCs, manages the channel's revocation window,
1279
// and also the htlc trickle queue+timer for this active channels.
1280
//
1281
// NOTE: This MUST be run as a goroutine.
1282
func (l *channelLink) htlcManager(ctx context.Context) {
216✔
1283
        defer func() {
423✔
1284
                l.cfg.BatchTicker.Stop()
207✔
1285
                l.cg.WgDone()
207✔
1286
                l.log.Infof("exited")
207✔
1287
        }()
207✔
1288

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

216✔
1291
        // Notify any clients that the link is now in the switch via an
216✔
1292
        // ActiveLinkEvent. We'll also defer an inactive link notification for
216✔
1293
        // when the link exits to ensure that every active notification is
216✔
1294
        // matched by an inactive one.
216✔
1295
        l.cfg.NotifyActiveLink(l.ChannelPoint())
216✔
1296
        defer l.cfg.NotifyInactiveLinkEvent(l.ChannelPoint())
216✔
1297

216✔
1298
        // If the link is not started for the first time, we need to take extra
216✔
1299
        // steps to resume its state.
216✔
1300
        err := l.resumeLink(ctx)
216✔
1301
        if err != nil {
220✔
1302
                l.log.Errorf("resuming link failed: %v", err)
4✔
1303
                return
4✔
1304
        }
4✔
1305

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

215✔
1313
        for {
4,438✔
1314
                // We must always check if we failed at some point processing
4,223✔
1315
                // the last update before processing the next.
4,223✔
1316
                if l.failed {
4,239✔
1317
                        l.log.Errorf("link failed, exiting htlcManager")
16✔
1318
                        return
16✔
1319
                }
16✔
1320

1321
                // Pause or resume the batch ticker.
1322
                l.toggleBatchTicker()
4,210✔
1323

4,210✔
1324
                select {
4,210✔
1325
                // We have a new hook that needs to be run when we reach a clean
1326
                // channel state.
1327
                case hook := <-l.flushHooks.newTransients:
4✔
1328
                        if l.channel.IsChannelClean() {
7✔
1329
                                hook()
3✔
1330
                        } else {
7✔
1331
                                l.flushHooks.alloc(hook)
4✔
1332
                        }
4✔
1333

1334
                // We have a new hook that needs to be run when we have
1335
                // committed all of our updates.
1336
                case hook := <-l.outgoingCommitHooks.newTransients:
4✔
1337
                        if !l.channel.OweCommitment() {
7✔
1338
                                hook()
3✔
1339
                        } else {
4✔
1340
                                l.outgoingCommitHooks.alloc(hook)
1✔
1341
                        }
1✔
1342

1343
                // We have a new hook that needs to be run when our peer has
1344
                // committed all of their updates.
1345
                case hook := <-l.incomingCommitHooks.newTransients:
×
1346
                        if !l.channel.NeedCommitment() {
×
1347
                                hook()
×
1348
                        } else {
×
1349
                                l.incomingCommitHooks.alloc(hook)
×
1350
                        }
×
1351

1352
                // Our update fee timer has fired, so we'll check the network
1353
                // fee to see if we should adjust our commitment fee.
1354
                case <-l.updateFeeTimer.C:
4✔
1355
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
4✔
1356
                        err := l.handleUpdateFee(ctx)
4✔
1357
                        if err != nil {
4✔
1358
                                l.log.Errorf("failed to handle update fee: "+
×
1359
                                        "%v", err)
×
1360
                        }
×
1361

1362
                // The underlying channel has notified us of a unilateral close
1363
                // carried out by the remote peer. In the case of such an
1364
                // event, we'll wipe the channel state from the peer, and mark
1365
                // the contract as fully settled. Afterwards we can exit.
1366
                //
1367
                // TODO(roasbeef): add force closure? also breach?
1368
                case <-l.cfg.ChainEvents.RemoteUnilateralClosure:
3✔
1369
                        l.log.Warnf("remote peer has closed on-chain")
3✔
1370

3✔
1371
                        // TODO(roasbeef): remove all together
3✔
1372
                        go func() {
6✔
1373
                                chanPoint := l.channel.ChannelPoint()
3✔
1374
                                l.cfg.Peer.WipeChannel(&chanPoint)
3✔
1375
                        }()
3✔
1376

1377
                        return
3✔
1378

1379
                case <-l.cfg.BatchTicker.Ticks():
202✔
1380
                        // Attempt to extend the remote commitment chain
202✔
1381
                        // including all the currently pending entries. If the
202✔
1382
                        // send was unsuccessful, then abandon the update,
202✔
1383
                        // waiting for the revocation window to open up.
202✔
1384
                        if !l.updateCommitTxOrFail(ctx) {
202✔
1385
                                return
×
1386
                        }
×
1387

1388
                case <-l.cfg.PendingCommitTicker.Ticks():
1✔
1389
                        l.failf(
1✔
1390
                                LinkFailureError{
1✔
1391
                                        code:          ErrRemoteUnresponsive,
1✔
1392
                                        FailureAction: LinkFailureDisconnect,
1✔
1393
                                },
1✔
1394
                                "unable to complete dance",
1✔
1395
                        )
1✔
1396
                        return
1✔
1397

1398
                // A message from the switch was just received. This indicates
1399
                // that the link is an intermediate hop in a multi-hop HTLC
1400
                // circuit.
1401
                case pkt := <-l.downstream:
524✔
1402
                        l.handleDownstreamPkt(ctx, pkt)
524✔
1403

1404
                // A message from the connected peer was just received. This
1405
                // indicates that we have a new incoming HTLC, either directly
1406
                // for us, or part of a multi-hop HTLC circuit.
1407
                case msg := <-l.upstream:
3,229✔
1408
                        l.handleUpstreamMsg(ctx, msg)
3,229✔
1409

1410
                // A htlc resolution is received. This means that we now have a
1411
                // resolution for a previously accepted htlc.
1412
                case hodlItem := <-l.hodlQueue.ChanOut():
58✔
1413
                        err := l.handleHtlcResolution(ctx, hodlItem)
58✔
1414
                        if err != nil {
59✔
1415
                                l.log.Errorf("failed to handle htlc "+
1✔
1416
                                        "resolution: %v", err)
1✔
1417
                        }
1✔
1418

1419
                // A user-initiated quiescence request is received. We now
1420
                // forward it to the quiescer.
1421
                case qReq := <-l.quiescenceReqs:
4✔
1422
                        err := l.handleQuiescenceReq(qReq)
4✔
1423
                        if err != nil {
4✔
1424
                                l.log.Errorf("failed handle quiescence "+
×
1425
                                        "req: %v", err)
×
1426
                        }
×
1427

1428
                case <-l.cg.Done():
192✔
1429
                        return
192✔
1430
                }
1431
        }
1432
}
1433

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

58✔
1440
        // Try to read all waiting resolution messages, so that they can all be
58✔
1441
        // processed in a single commitment tx update.
58✔
1442
        htlcResolution := firstResolution
58✔
1443
loop:
58✔
1444
        for {
116✔
1445
                // Lookup all hodl htlcs that can be failed or settled with this event.
58✔
1446
                // The hodl htlc must be present in the map.
58✔
1447
                circuitKey := htlcResolution.CircuitKey()
58✔
1448
                hodlHtlc, ok := l.hodlMap[circuitKey]
58✔
1449
                if !ok {
58✔
1450
                        return fmt.Errorf("hodl htlc not found: %v", circuitKey)
×
1451
                }
×
1452

1453
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
58✔
1454
                        return err
×
1455
                }
×
1456

1457
                // Clean up hodl map.
1458
                delete(l.hodlMap, circuitKey)
58✔
1459

58✔
1460
                select {
58✔
1461
                case item := <-l.hodlQueue.ChanOut():
3✔
1462
                        htlcResolution = item.(invoices.HtlcResolution)
3✔
1463

1464
                // No need to process it if the link is broken.
1465
                case <-l.cg.Done():
×
1466
                        return ErrLinkShuttingDown
×
1467

1468
                default:
58✔
1469
                        break loop
58✔
1470
                }
1471
        }
1472

1473
        // Update the commitment tx.
1474
        if err := l.updateCommitTx(ctx); err != nil {
59✔
1475
                return err
1✔
1476
        }
1✔
1477

1478
        return nil
57✔
1479
}
1480

1481
// processHtlcResolution applies a received htlc resolution to the provided
1482
// htlc. When this function returns without an error, the commit tx should be
1483
// updated.
1484
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1485
        htlc hodlHtlc) error {
204✔
1486

204✔
1487
        circuitKey := resolution.CircuitKey()
204✔
1488

204✔
1489
        // Determine required action for the resolution based on the type of
204✔
1490
        // resolution we have received.
204✔
1491
        switch res := resolution.(type) {
204✔
1492
        // Settle htlcs that returned a settle resolution using the preimage
1493
        // in the resolution.
1494
        case *invoices.HtlcSettleResolution:
200✔
1495
                l.log.Debugf("received settle resolution for %v "+
200✔
1496
                        "with outcome: %v", circuitKey, res.Outcome)
200✔
1497

200✔
1498
                return l.settleHTLC(
200✔
1499
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
200✔
1500
                )
200✔
1501

1502
        // For htlc failures, we get the relevant failure message based
1503
        // on the failure resolution and then fail the htlc.
1504
        case *invoices.HtlcFailResolution:
7✔
1505
                l.log.Debugf("received cancel resolution for "+
7✔
1506
                        "%v with outcome: %v", circuitKey, res.Outcome)
7✔
1507

7✔
1508
                // Get the lnwire failure message based on the resolution
7✔
1509
                // result.
7✔
1510
                failure := getResolutionFailure(res, htlc.add.Amount)
7✔
1511

7✔
1512
                l.sendHTLCError(
7✔
1513
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
7✔
1514
                        true,
7✔
1515
                )
7✔
1516
                return nil
7✔
1517

1518
        // Fail if we do not get a settle of fail resolution, since we
1519
        // are only expecting to handle settles and fails.
1520
        default:
×
1521
                return fmt.Errorf("unknown htlc resolution type: %T",
×
1522
                        resolution)
×
1523
        }
1524
}
1525

1526
// getResolutionFailure returns the wire message that a htlc resolution should
1527
// be failed with.
1528
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1529
        amount lnwire.MilliSatoshi) *LinkError {
7✔
1530

7✔
1531
        // If the resolution has been resolved as part of a MPP timeout,
7✔
1532
        // we need to fail the htlc with lnwire.FailMppTimeout.
7✔
1533
        if resolution.Outcome == invoices.ResultMppTimeout {
7✔
1534
                return NewDetailedLinkError(
×
1535
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
1536
                )
×
1537
        }
×
1538

1539
        // If the htlc is not a MPP timeout, we fail it with
1540
        // FailIncorrectDetails. This error is sent for invoice payment
1541
        // failures such as underpayment/ expiry too soon and hodl invoices
1542
        // (which return FailIncorrectDetails to avoid leaking information).
1543
        incorrectDetails := lnwire.NewFailIncorrectDetails(
7✔
1544
                amount, uint32(resolution.AcceptHeight),
7✔
1545
        )
7✔
1546

7✔
1547
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
7✔
1548
}
1549

1550
// randomFeeUpdateTimeout returns a random timeout between the bounds defined
1551
// within the link's configuration that will be used to determine when the link
1552
// should propose an update to its commitment fee rate.
1553
func (l *channelLink) randomFeeUpdateTimeout() time.Duration {
220✔
1554
        lower := int64(l.cfg.MinUpdateTimeout)
220✔
1555
        upper := int64(l.cfg.MaxUpdateTimeout)
220✔
1556
        return time.Duration(prand.Int63n(upper-lower) + lower)
220✔
1557
}
220✔
1558

1559
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1560
// downstream HTLC Switch.
1561
func (l *channelLink) handleDownstreamUpdateAdd(ctx context.Context,
1562
        pkt *htlcPacket) error {
483✔
1563

483✔
1564
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
483✔
1565
        if !ok {
483✔
1566
                return errors.New("not an UpdateAddHTLC packet")
×
1567
        }
×
1568

1569
        // If we are flushing the link in the outgoing direction or we have
1570
        // already sent Stfu, then we can't add new htlcs to the link and we
1571
        // need to bounce it.
1572
        if l.IsFlushing(Outgoing) || !l.quiescer.CanSendUpdates() {
483✔
1573
                l.mailBox.FailAdd(pkt)
×
1574

×
1575
                return NewDetailedLinkError(
×
1576
                        &lnwire.FailTemporaryChannelFailure{},
×
1577
                        OutgoingFailureLinkNotEligible,
×
1578
                )
×
1579
        }
×
1580

1581
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1582
        // arbitrary delays between the switch adding an ADD to the
1583
        // mailbox, and the HTLC being added to the commitment state.
1584
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
483✔
1585
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
1586
                l.mailBox.AckPacket(pkt.inKey())
×
1587
                return nil
×
1588
        }
×
1589

1590
        // Check if we can add the HTLC here without exceededing the max fee
1591
        // exposure threshold.
1592
        if l.isOverexposedWithHtlc(htlc, false) {
487✔
1593
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1594
                        "exposure exceeded")
4✔
1595

4✔
1596
                l.mailBox.FailAdd(pkt)
4✔
1597

4✔
1598
                return NewDetailedLinkError(
4✔
1599
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1600
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1601
                )
4✔
1602
        }
4✔
1603

1604
        // A new payment has been initiated via the downstream channel,
1605
        // so we add the new HTLC to our local log, then update the
1606
        // commitment chains.
1607
        htlc.ChanID = l.ChanID()
479✔
1608
        openCircuitRef := pkt.inKey()
479✔
1609

479✔
1610
        // We enforce the fee buffer for the commitment transaction because
479✔
1611
        // we are in control of adding this htlc. Nothing has locked-in yet so
479✔
1612
        // we can securely enforce the fee buffer which is only relevant if we
479✔
1613
        // are the initiator of the channel.
479✔
1614
        index, err := l.channel.AddHTLC(htlc, &openCircuitRef)
479✔
1615
        if err != nil {
482✔
1616
                // The HTLC was unable to be added to the state machine,
3✔
1617
                // as a result, we'll signal the switch to cancel the
3✔
1618
                // pending payment.
3✔
1619
                l.log.Warnf("Unable to handle downstream add HTLC: %v",
3✔
1620
                        err)
3✔
1621

3✔
1622
                // Remove this packet from the link's mailbox, this
3✔
1623
                // prevents it from being reprocessed if the link
3✔
1624
                // restarts and resets it mailbox. If this response
3✔
1625
                // doesn't make it back to the originating link, it will
3✔
1626
                // be rejected upon attempting to reforward the Add to
3✔
1627
                // the switch, since the circuit was never fully opened,
3✔
1628
                // and the forwarding package shows it as
3✔
1629
                // unacknowledged.
3✔
1630
                l.mailBox.FailAdd(pkt)
3✔
1631

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

1638
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
478✔
1639
                "local_log_index=%v, pend_updates=%v",
478✔
1640
                htlc.PaymentHash[:], index,
478✔
1641
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
478✔
1642

478✔
1643
        pkt.outgoingChanID = l.ShortChanID()
478✔
1644
        pkt.outgoingHTLCID = index
478✔
1645
        htlc.ID = index
478✔
1646

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

478✔
1650
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
478✔
1651
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
478✔
1652

478✔
1653
        err = l.cfg.Peer.SendMessage(false, htlc)
478✔
1654
        if err != nil {
478✔
1655
                l.log.Errorf("failed to send UpdateAddHTLC: %v", err)
×
1656
        }
×
1657

1658
        // Send a forward event notification to htlcNotifier.
1659
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
478✔
1660
                newHtlcKey(pkt),
478✔
1661
                HtlcInfo{
478✔
1662
                        IncomingTimeLock: pkt.incomingTimeout,
478✔
1663
                        IncomingAmt:      pkt.incomingAmount,
478✔
1664
                        OutgoingTimeLock: htlc.Expiry,
478✔
1665
                        OutgoingAmt:      htlc.Amount,
478✔
1666
                },
478✔
1667
                getEventType(pkt),
478✔
1668
        )
478✔
1669

478✔
1670
        l.tryBatchUpdateCommitTx(ctx)
478✔
1671

478✔
1672
        return nil
478✔
1673
}
1674

1675
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1676
// Switch. Possible messages sent by the switch include requests to forward new
1677
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1678
// cleared HTLCs with the upstream peer.
1679
//
1680
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1681
func (l *channelLink) handleDownstreamPkt(ctx context.Context,
1682
        pkt *htlcPacket) {
524✔
1683

524✔
1684
        if pkt.htlc.MsgType().IsChannelUpdate() &&
524✔
1685
                !l.quiescer.CanSendUpdates() {
524✔
1686

×
1687
                l.log.Warnf("unable to process channel update. "+
×
1688
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1689

×
1690
                return
×
1691
        }
×
1692

1693
        switch htlc := pkt.htlc.(type) {
524✔
1694
        case *lnwire.UpdateAddHTLC:
483✔
1695
                // Handle add message. The returned error can be ignored,
483✔
1696
                // because it is also sent through the mailbox.
483✔
1697
                _ = l.handleDownstreamUpdateAdd(ctx, pkt)
483✔
1698

1699
        case *lnwire.UpdateFulfillHTLC:
26✔
1700
                l.processLocalUpdateFulfillHTLC(ctx, pkt, htlc)
26✔
1701

1702
        case *lnwire.UpdateFailHTLC:
21✔
1703
                l.processLocalUpdateFailHTLC(ctx, pkt, htlc)
21✔
1704
        }
1705
}
1706

1707
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1708
// full.
1709
func (l *channelLink) tryBatchUpdateCommitTx(ctx context.Context) {
478✔
1710
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
478✔
1711
        if pending < uint64(l.cfg.BatchSize) {
930✔
1712
                return
452✔
1713
        }
452✔
1714

1715
        l.updateCommitTxOrFail(ctx)
29✔
1716
}
1717

1718
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1719
// associated with this packet. If successful in doing so, it will also purge
1720
// the open circuit from the circuit map and remove the packet from the link's
1721
// mailbox.
1722
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
2✔
1723
        inKey := pkt.inKey()
2✔
1724

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

2✔
1728
        // If the htlc packet doesn't have a source reference, it is unsafe to
2✔
1729
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
2✔
1730
        if pkt.sourceRef == nil {
3✔
1731
                l.log.Errorf("unable to cleanup response for incoming "+
1✔
1732
                        "circuit-key=%v, does not contain source reference",
1✔
1733
                        inKey)
1✔
1734
                return
1✔
1735
        }
1✔
1736

1737
        // If the source reference is present,  we will try to prevent this link
1738
        // from resending the packet to the switch. To do so, we ack the AddRef
1739
        // of the incoming HTLC belonging to this link.
1740
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
1✔
1741
        if err != nil {
1✔
1742
                l.log.Errorf("unable to ack AddRef for incoming "+
×
1743
                        "circuit-key=%v: %v", inKey, err)
×
1744

×
1745
                // If this operation failed, it is unsafe to attempt removal of
×
1746
                // the destination reference or circuit, so we exit early. The
×
1747
                // cleanup may proceed with a different packet in the future
×
1748
                // that succeeds on this step.
×
1749
                return
×
1750
        }
×
1751

1752
        // Now that we know this link will stop retransmitting Adds to the
1753
        // switch, we can begin to teardown the response reference and circuit
1754
        // map.
1755
        //
1756
        // If the packet includes a destination reference, then a response for
1757
        // this HTLC was locked into the outgoing channel. Attempt to remove
1758
        // this reference, so we stop retransmitting the response internally.
1759
        // Even if this fails, we will proceed in trying to delete the circuit.
1760
        // When retransmitting responses, the destination references will be
1761
        // cleaned up if an open circuit is not found in the circuit map.
1762
        if pkt.destRef != nil {
1✔
1763
                err := l.channel.AckSettleFails(*pkt.destRef)
×
1764
                if err != nil {
×
1765
                        l.log.Errorf("unable to ack SettleFailRef "+
×
1766
                                "for incoming circuit-key=%v: %v",
×
1767
                                inKey, err)
×
1768
                }
×
1769
        }
1770

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

1✔
1773
        // With all known references acked, we can now safely delete the circuit
1✔
1774
        // from the switch's circuit map, as the state is no longer needed.
1✔
1775
        err = l.cfg.Circuits.DeleteCircuits(inKey)
1✔
1776
        if err != nil {
1✔
1777
                l.log.Errorf("unable to delete circuit for "+
×
1778
                        "circuit-key=%v: %v", inKey, err)
×
1779
        }
×
1780
}
1781

1782
// handleUpstreamMsg processes wire messages related to commitment state
1783
// updates from the upstream peer. The upstream peer is the peer whom we have a
1784
// direct channel with, updating our respective commitment chains.
1785
func (l *channelLink) handleUpstreamMsg(ctx context.Context,
1786
        msg lnwire.Message) {
3,229✔
1787

3,229✔
1788
        l.log.Tracef("receive upstream msg %v, handling now... ", msg.MsgType())
3,229✔
1789
        defer l.log.Tracef("handled upstream msg %v", msg.MsgType())
3,229✔
1790

3,229✔
1791
        // First check if the message is an update and we are capable of
3,229✔
1792
        // receiving updates right now.
3,229✔
1793
        if msg.MsgType().IsChannelUpdate() && !l.quiescer.CanRecvUpdates() {
3,229✔
1794
                l.stfuFailf("update received after stfu: %T", msg)
×
1795
                return
×
1796
        }
×
1797

1798
        var err error
3,229✔
1799

3,229✔
1800
        switch msg := msg.(type) {
3,229✔
1801
        case *lnwire.UpdateAddHTLC:
453✔
1802
                err = l.processRemoteUpdateAddHTLC(msg)
453✔
1803

1804
        case *lnwire.UpdateFulfillHTLC:
230✔
1805
                err = l.processRemoteUpdateFulfillHTLC(msg)
230✔
1806

1807
        case *lnwire.UpdateFailMalformedHTLC:
6✔
1808
                err = l.processRemoteUpdateFailMalformedHTLC(msg)
6✔
1809

1810
        case *lnwire.UpdateFailHTLC:
123✔
1811
                err = l.processRemoteUpdateFailHTLC(msg)
123✔
1812

1813
        case *lnwire.CommitSig:
1,219✔
1814
                err = l.processRemoteCommitSig(ctx, msg)
1,219✔
1815

1816
        case *lnwire.RevokeAndAck:
1,207✔
1817
                err = l.processRemoteRevokeAndAck(ctx, msg)
1,207✔
1818

1819
        case *lnwire.UpdateFee:
3✔
1820
                err = l.processRemoteUpdateFee(msg)
3✔
1821

1822
        case *lnwire.Stfu:
5✔
1823
                err = l.handleStfu(msg)
5✔
1824
                if err != nil {
5✔
1825
                        l.stfuFailf("handleStfu: %v", err)
×
1826
                }
×
1827

1828
        // In the case where we receive a warning message from our peer, just
1829
        // log it and move on. We choose not to disconnect from our peer,
1830
        // although we "MAY" do so according to the specification.
1831
        case *lnwire.Warning:
1✔
1832
                l.log.Warnf("received warning message from peer: %v",
1✔
1833
                        msg.Warning())
1✔
1834

1835
        case *lnwire.Error:
2✔
1836
                l.processRemoteError(msg)
2✔
1837

1838
        default:
×
1839
                l.log.Warnf("received unknown message of type %T", msg)
×
1840
        }
1841

1842
        if err != nil {
3,234✔
1843
                l.log.Errorf("failed to process remote %v: %v", msg.MsgType(),
5✔
1844
                        err)
5✔
1845
        }
5✔
1846
}
1847

1848
// handleStfu implements the top-level logic for handling the Stfu message from
1849
// our peer.
1850
func (l *channelLink) handleStfu(stfu *lnwire.Stfu) error {
5✔
1851
        if !l.noDanglingUpdates(lntypes.Remote) {
5✔
1852
                return ErrPendingRemoteUpdates
×
1853
        }
×
1854
        err := l.quiescer.RecvStfu(*stfu)
5✔
1855
        if err != nil {
5✔
1856
                return err
×
1857
        }
×
1858

1859
        // If we can immediately send an Stfu response back, we will.
1860
        if l.noDanglingUpdates(lntypes.Local) {
9✔
1861
                return l.quiescer.SendOwedStfu()
4✔
1862
        }
4✔
1863

1864
        return nil
1✔
1865
}
1866

1867
// stfuFailf fails the link in the case where the requirements of the quiescence
1868
// protocol are violated. In all cases we opt to drop the connection as only
1869
// link state (as opposed to channel state) is affected.
1870
func (l *channelLink) stfuFailf(format string, args ...interface{}) {
×
1871
        l.failf(LinkFailureError{
×
1872
                code:             ErrStfuViolation,
×
1873
                FailureAction:    LinkFailureDisconnect,
×
1874
                PermanentFailure: false,
×
1875
                Warning:          true,
×
1876
        }, format, args...)
×
1877
}
×
1878

1879
// noDanglingUpdates returns true when there are 0 updates that were originally
1880
// issued by whose on either the Local or Remote commitment transaction.
1881
func (l *channelLink) noDanglingUpdates(whose lntypes.ChannelParty) bool {
1,223✔
1882
        pendingOnLocal := l.channel.NumPendingUpdates(
1,223✔
1883
                whose, lntypes.Local,
1,223✔
1884
        )
1,223✔
1885
        pendingOnRemote := l.channel.NumPendingUpdates(
1,223✔
1886
                whose, lntypes.Remote,
1,223✔
1887
        )
1,223✔
1888

1,223✔
1889
        return pendingOnLocal == 0 && pendingOnRemote == 0
1,223✔
1890
}
1,223✔
1891

1892
// ackDownStreamPackets is responsible for removing htlcs from a link's mailbox
1893
// for packets delivered from server, and cleaning up any circuits closed by
1894
// signing a previous commitment txn. This method ensures that the circuits are
1895
// removed from the circuit map before removing them from the link's mailbox,
1896
// otherwise it could be possible for some circuit to be missed if this link
1897
// flaps.
1898
func (l *channelLink) ackDownStreamPackets() error {
1,398✔
1899
        // First, remove the downstream Add packets that were included in the
1,398✔
1900
        // previous commitment signature. This will prevent the Adds from being
1,398✔
1901
        // replayed if this link disconnects.
1,398✔
1902
        for _, inKey := range l.openedCircuits {
1,865✔
1903
                // In order to test the sphinx replay logic of the remote
467✔
1904
                // party, unsafe replay does not acknowledge the packets from
467✔
1905
                // the mailbox. We can then force a replay of any Add packets
467✔
1906
                // held in memory by disconnecting and reconnecting the link.
467✔
1907
                if l.cfg.UnsafeReplay {
470✔
1908
                        continue
3✔
1909
                }
1910

1911
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
467✔
1912
                l.mailBox.AckPacket(inKey)
467✔
1913
        }
1914

1915
        // Now, we will delete all circuits closed by the previous commitment
1916
        // signature, which is the result of downstream Settle/Fail packets. We
1917
        // batch them here to ensure circuits are closed atomically and for
1918
        // performance.
1919
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
1,398✔
1920
        switch err {
1,398✔
1921
        case nil:
1,398✔
1922
                // Successful deletion.
1923

1924
        default:
×
1925
                l.log.Errorf("unable to delete %d circuits: %v",
×
1926
                        len(l.closedCircuits), err)
×
1927
                return err
×
1928
        }
1929

1930
        // With the circuits removed from memory and disk, we now ack any
1931
        // Settle/Fails in the mailbox to ensure they do not get redelivered
1932
        // after startup. If forgive is enabled and we've reached this point,
1933
        // the circuits must have been removed at some point, so it is now safe
1934
        // to un-queue the corresponding Settle/Fails.
1935
        for _, inKey := range l.closedCircuits {
1,440✔
1936
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
42✔
1937
                        inKey)
42✔
1938
                l.mailBox.AckPacket(inKey)
42✔
1939
        }
42✔
1940

1941
        // Lastly, reset our buffers to be empty while keeping any acquired
1942
        // growth in the backing array.
1943
        l.openedCircuits = l.openedCircuits[:0]
1,398✔
1944
        l.closedCircuits = l.closedCircuits[:0]
1,398✔
1945

1,398✔
1946
        return nil
1,398✔
1947
}
1948

1949
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
1950
// the link.
1951
func (l *channelLink) updateCommitTxOrFail(ctx context.Context) bool {
1,260✔
1952
        err := l.updateCommitTx(ctx)
1,260✔
1953
        switch {
1,260✔
1954
        // No error encountered, success.
1955
        case err == nil:
1,250✔
1956

1957
        // A duplicate keystone error should be resolved and is not fatal, so
1958
        // we won't send an Error message to the peer.
1959
        case errors.Is(err, ErrDuplicateKeystone):
×
1960
                l.failf(LinkFailureError{code: ErrCircuitError},
×
1961
                        "temporary circuit error: %v", err)
×
1962
                return false
×
1963

1964
        // Any other error is treated results in an Error message being sent to
1965
        // the peer.
1966
        default:
10✔
1967
                l.failf(LinkFailureError{code: ErrInternalError},
10✔
1968
                        "unable to update commitment: %v", err)
10✔
1969
                return false
10✔
1970
        }
1971

1972
        return true
1,250✔
1973
}
1974

1975
// updateCommitTx signs, then sends an update to the remote peer adding a new
1976
// commitment to their commitment chain which includes all the latest updates
1977
// we've received+processed up to this point.
1978
func (l *channelLink) updateCommitTx(ctx context.Context) error {
1,318✔
1979
        // Preemptively write all pending keystones to disk, just in case the
1,318✔
1980
        // HTLCs we have in memory are included in the subsequent attempt to
1,318✔
1981
        // sign a commitment state.
1,318✔
1982
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
1,318✔
1983
        if err != nil {
1,318✔
1984
                // If ErrDuplicateKeystone is returned, the caller will catch
×
1985
                // it.
×
1986
                return err
×
1987
        }
×
1988

1989
        // Reset the batch, but keep the backing buffer to avoid reallocating.
1990
        l.keystoneBatch = l.keystoneBatch[:0]
1,318✔
1991

1,318✔
1992
        // If hodl.Commit mode is active, we will refrain from attempting to
1,318✔
1993
        // commit any in-memory modifications to the channel state. Exiting here
1,318✔
1994
        // permits testing of either the switch or link's ability to trim
1,318✔
1995
        // circuits that have been opened, but unsuccessfully committed.
1,318✔
1996
        if l.cfg.HodlMask.Active(hodl.Commit) {
1,325✔
1997
                l.log.Warnf(hodl.Commit.Warning())
7✔
1998
                return nil
7✔
1999
        }
7✔
2000

2001
        ctx, done := l.cg.Create(ctx)
1,314✔
2002
        defer done()
1,314✔
2003

1,314✔
2004
        newCommit, err := l.channel.SignNextCommitment(ctx)
1,314✔
2005
        if err == lnwallet.ErrNoWindow {
1,403✔
2006
                l.cfg.PendingCommitTicker.Resume()
89✔
2007
                l.log.Trace("PendingCommitTicker resumed")
89✔
2008

89✔
2009
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
89✔
2010
                l.log.Tracef("revocation window exhausted, unable to send: "+
89✔
2011
                        "%v, pend_updates=%v, dangling_closes%v", n,
89✔
2012
                        lnutils.SpewLogClosure(l.openedCircuits),
89✔
2013
                        lnutils.SpewLogClosure(l.closedCircuits))
89✔
2014

89✔
2015
                return nil
89✔
2016
        } else if err != nil {
1,317✔
2017
                return err
×
2018
        }
×
2019

2020
        if err := l.ackDownStreamPackets(); err != nil {
1,228✔
2021
                return err
×
2022
        }
×
2023

2024
        l.cfg.PendingCommitTicker.Pause()
1,228✔
2025
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
1,228✔
2026

1,228✔
2027
        // The remote party now has a new pending commitment, so we'll update
1,228✔
2028
        // the contract court to be aware of this new set (the prior old remote
1,228✔
2029
        // pending).
1,228✔
2030
        newUpdate := &contractcourt.ContractUpdate{
1,228✔
2031
                HtlcKey: contractcourt.RemotePendingHtlcSet,
1,228✔
2032
                Htlcs:   newCommit.PendingHTLCs,
1,228✔
2033
        }
1,228✔
2034
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,228✔
2035
        if err != nil {
1,228✔
2036
                l.log.Errorf("unable to notify contract update: %v", err)
×
2037
                return err
×
2038
        }
×
2039

2040
        select {
1,228✔
2041
        case <-l.cg.Done():
11✔
2042
                return ErrLinkShuttingDown
11✔
2043
        default:
1,217✔
2044
        }
2045

2046
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
1,217✔
2047
        if err != nil {
1,217✔
2048
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
2049
        }
×
2050

2051
        commitSig := &lnwire.CommitSig{
1,217✔
2052
                ChanID:        l.ChanID(),
1,217✔
2053
                CommitSig:     newCommit.CommitSig,
1,217✔
2054
                HtlcSigs:      newCommit.HtlcSigs,
1,217✔
2055
                PartialSig:    newCommit.PartialSig,
1,217✔
2056
                CustomRecords: auxBlobRecords,
1,217✔
2057
        }
1,217✔
2058
        err = l.cfg.Peer.SendMessage(false, commitSig)
1,217✔
2059
        if err != nil {
1,217✔
UNCOV
2060
                l.log.Errorf("failed to send CommitSig: %v", err)
×
UNCOV
2061
        }
×
2062

2063
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
2064
        // of commit hooks.
2065
        l.RWMutex.Lock()
1,217✔
2066
        l.outgoingCommitHooks.invoke()
1,217✔
2067
        l.RWMutex.Unlock()
1,217✔
2068

1,217✔
2069
        return nil
1,217✔
2070
}
2071

2072
// Peer returns the representation of remote peer with which we have the
2073
// channel link opened.
2074
//
2075
// NOTE: Part of the ChannelLink interface.
2076
func (l *channelLink) PeerPubKey() [33]byte {
444✔
2077
        return l.cfg.Peer.PubKey()
444✔
2078
}
444✔
2079

2080
// ChannelPoint returns the channel outpoint for the channel link.
2081
// NOTE: Part of the ChannelLink interface.
2082
func (l *channelLink) ChannelPoint() wire.OutPoint {
853✔
2083
        return l.channel.ChannelPoint()
853✔
2084
}
853✔
2085

2086
// ShortChanID returns the short channel ID for the channel link. The short
2087
// channel ID encodes the exact location in the main chain that the original
2088
// funding output can be found.
2089
//
2090
// NOTE: Part of the ChannelLink interface.
2091
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
4,251✔
2092
        l.RLock()
4,251✔
2093
        defer l.RUnlock()
4,251✔
2094

4,251✔
2095
        return l.channel.ShortChanID()
4,251✔
2096
}
4,251✔
2097

2098
// UpdateShortChanID updates the short channel ID for a link. This may be
2099
// required in the event that a link is created before the short chan ID for it
2100
// is known, or a re-org occurs, and the funding transaction changes location
2101
// within the chain.
2102
//
2103
// NOTE: Part of the ChannelLink interface.
2104
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
3✔
2105
        chanID := l.ChanID()
3✔
2106

3✔
2107
        // Refresh the channel state's short channel ID by loading it from disk.
3✔
2108
        // This ensures that the channel state accurately reflects the updated
3✔
2109
        // short channel ID.
3✔
2110
        err := l.channel.State().Refresh()
3✔
2111
        if err != nil {
3✔
2112
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
2113
                        "%v", chanID, err)
×
2114
                return hop.Source, err
×
2115
        }
×
2116

2117
        return hop.Source, nil
3✔
2118
}
2119

2120
// ChanID returns the channel ID for the channel link. The channel ID is a more
2121
// compact representation of a channel's full outpoint.
2122
//
2123
// NOTE: Part of the ChannelLink interface.
2124
func (l *channelLink) ChanID() lnwire.ChannelID {
3,957✔
2125
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
3,957✔
2126
}
3,957✔
2127

2128
// Bandwidth returns the total amount that can flow through the channel link at
2129
// this given instance. The value returned is expressed in millisatoshi and can
2130
// be used by callers when making forwarding decisions to determine if a link
2131
// can accept an HTLC.
2132
//
2133
// NOTE: Part of the ChannelLink interface.
2134
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
814✔
2135
        // Get the balance available on the channel for new HTLCs. This takes
814✔
2136
        // the channel reserve into account so HTLCs up to this value won't
814✔
2137
        // violate it.
814✔
2138
        return l.channel.AvailableBalance()
814✔
2139
}
814✔
2140

2141
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2142
// amount provided to the link. This check does not reserve a space, since
2143
// forwards or other payments may use the available slot, so it should be
2144
// considered best-effort.
2145
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
3✔
2146
        return l.channel.MayAddOutgoingHtlc(amt)
3✔
2147
}
3✔
2148

2149
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2150
// method.
2151
//
2152
// NOTE: Part of the dustHandler interface.
2153
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2154
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
2,526✔
2155

2,526✔
2156
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
2,526✔
2157
}
2,526✔
2158

2159
// getFeeRate is a wrapper method that retrieves the underlying channel's
2160
// feerate.
2161
//
2162
// NOTE: Part of the dustHandler interface.
2163
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
672✔
2164
        return l.channel.CommitFeeRate()
672✔
2165
}
672✔
2166

2167
// getDustClosure returns a closure that can be used by the switch or mailbox
2168
// to evaluate whether a given HTLC is dust.
2169
//
2170
// NOTE: Part of the dustHandler interface.
2171
func (l *channelLink) getDustClosure() dustClosure {
1,602✔
2172
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
1,602✔
2173
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
1,602✔
2174
        chanType := l.channel.State().ChanType
1,602✔
2175

1,602✔
2176
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
1,602✔
2177
}
1,602✔
2178

2179
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2180
// is used so that the Switch can have access to the commitment fee without
2181
// needing to have a *LightningChannel. This doesn't include dust.
2182
//
2183
// NOTE: Part of the dustHandler interface.
2184
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
1,897✔
2185
        if remote {
2,864✔
2186
                return l.channel.State().RemoteCommitment.CommitFee
967✔
2187
        }
967✔
2188

2189
        return l.channel.State().LocalCommitment.CommitFee
933✔
2190
}
2191

2192
// exceedsFeeExposureLimit returns whether or not the new proposed fee-rate
2193
// increases the total dust and fees within the channel past the configured
2194
// fee threshold. It first calculates the dust sum over every update in the
2195
// update log with the proposed fee-rate and taking into account both the local
2196
// and remote dust limits. It uses every update in the update log instead of
2197
// what is actually on the local and remote commitments because it is assumed
2198
// that in a worst-case scenario, every update in the update log could
2199
// theoretically be on either commitment transaction and this needs to be
2200
// accounted for with this fee-rate. It then calculates the local and remote
2201
// commitment fees given the proposed fee-rate. Finally, it tallies the results
2202
// and determines if the fee threshold has been exceeded.
2203
func (l *channelLink) exceedsFeeExposureLimit(
2204
        feePerKw chainfee.SatPerKWeight) (bool, error) {
6✔
2205

6✔
2206
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
6✔
2207

6✔
2208
        // Get the sum of dust for both the local and remote commitments using
6✔
2209
        // this "dry-run" fee.
6✔
2210
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
6✔
2211
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
6✔
2212

6✔
2213
        // Calculate the local and remote commitment fees using this dry-run
6✔
2214
        // fee.
6✔
2215
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
2216
        if err != nil {
6✔
2217
                return false, err
×
2218
        }
×
2219

2220
        // Finally, check whether the max fee exposure was exceeded on either
2221
        // future commitment transaction with the fee-rate.
2222
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
6✔
2223
        if totalLocalDust > l.cfg.MaxFeeExposure {
6✔
2224
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
2225
                        "local dust: %v, local fee: %v", l.ShortChanID(),
×
2226
                        totalLocalDust, localFee)
×
2227

×
2228
                return true, nil
×
2229
        }
×
2230

2231
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
6✔
2232
                remoteFee,
6✔
2233
        )
6✔
2234

6✔
2235
        if totalRemoteDust > l.cfg.MaxFeeExposure {
6✔
2236
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
2237
                        "remote dust: %v, remote fee: %v", l.ShortChanID(),
×
2238
                        totalRemoteDust, remoteFee)
×
2239

×
2240
                return true, nil
×
2241
        }
×
2242

2243
        return false, nil
6✔
2244
}
2245

2246
// isOverexposedWithHtlc calculates whether the proposed HTLC will make the
2247
// channel exceed the fee threshold. It first fetches the largest fee-rate that
2248
// may be on any unrevoked commitment transaction. Then, using this fee-rate,
2249
// determines if the to-be-added HTLC is dust. If the HTLC is dust, it adds to
2250
// the overall dust sum. If it is not dust, it contributes to weight, which
2251
// also adds to the overall dust sum by an increase in fees. If the dust sum on
2252
// either commitment exceeds the configured fee threshold, this function
2253
// returns true.
2254
func (l *channelLink) isOverexposedWithHtlc(htlc *lnwire.UpdateAddHTLC,
2255
        incoming bool) bool {
933✔
2256

933✔
2257
        dustClosure := l.getDustClosure()
933✔
2258

933✔
2259
        feeRate := l.channel.WorstCaseFeeRate()
933✔
2260

933✔
2261
        amount := htlc.Amount.ToSatoshis()
933✔
2262

933✔
2263
        // See if this HTLC is dust on both the local and remote commitments.
933✔
2264
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
933✔
2265
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
933✔
2266

933✔
2267
        // Calculate the dust sum for the local and remote commitments.
933✔
2268
        localDustSum := l.getDustSum(
933✔
2269
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
933✔
2270
        )
933✔
2271
        remoteDustSum := l.getDustSum(
933✔
2272
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
933✔
2273
        )
933✔
2274

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

933✔
2278
        if l.getCommitFee(true) > commitFee {
968✔
2279
                commitFee = l.getCommitFee(true)
35✔
2280
        }
35✔
2281

2282
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
933✔
2283

933✔
2284
        localDustSum += commitFeeMSat
933✔
2285
        remoteDustSum += commitFeeMSat
933✔
2286

933✔
2287
        // Calculate the additional fee increase if this is a non-dust HTLC.
933✔
2288
        weight := lntypes.WeightUnit(input.HTLCWeight)
933✔
2289
        additional := lnwire.NewMSatFromSatoshis(
933✔
2290
                feeRate.FeeForWeight(weight),
933✔
2291
        )
933✔
2292

933✔
2293
        if isLocalDust {
1,569✔
2294
                // If this is dust, it doesn't contribute to weight but does
636✔
2295
                // contribute to the overall dust sum.
636✔
2296
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
636✔
2297
        } else {
936✔
2298
                // Account for the fee increase that comes with an increase in
300✔
2299
                // weight.
300✔
2300
                localDustSum += additional
300✔
2301
        }
300✔
2302

2303
        if localDustSum > l.cfg.MaxFeeExposure {
937✔
2304
                // The max fee exposure was exceeded.
4✔
2305
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
4✔
2306
                        "overexposed, total local dust: %v (current commit "+
4✔
2307
                        "fee: %v)", l.ShortChanID(), htlc, localDustSum)
4✔
2308

4✔
2309
                return true
4✔
2310
        }
4✔
2311

2312
        if isRemoteDust {
1,562✔
2313
                // If this is dust, it doesn't contribute to weight but does
633✔
2314
                // contribute to the overall dust sum.
633✔
2315
                remoteDustSum += lnwire.NewMSatFromSatoshis(amount)
633✔
2316
        } else {
932✔
2317
                // Account for the fee increase that comes with an increase in
299✔
2318
                // weight.
299✔
2319
                remoteDustSum += additional
299✔
2320
        }
299✔
2321

2322
        if remoteDustSum > l.cfg.MaxFeeExposure {
929✔
2323
                // The max fee exposure was exceeded.
×
2324
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
2325
                        "overexposed, total remote dust: %v (current commit "+
×
2326
                        "fee: %v)", l.ShortChanID(), htlc, remoteDustSum)
×
2327

×
2328
                return true
×
2329
        }
×
2330

2331
        return false
929✔
2332
}
2333

2334
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
2335
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
2336
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
2337
// whether to evaluate on the local or remote commit, and finally an HTLC
2338
// amount to test.
2339
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
2340
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
2341

2342
// dustHelper is used to construct the dustClosure.
2343
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
2344
        remoteDustLimit btcutil.Amount) dustClosure {
1,802✔
2345

1,802✔
2346
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
1,802✔
2347
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
11,461✔
2348

9,659✔
2349
                var dustLimit btcutil.Amount
9,659✔
2350
                if whoseCommit.IsLocal() {
14,490✔
2351
                        dustLimit = localDustLimit
4,831✔
2352
                } else {
9,662✔
2353
                        dustLimit = remoteDustLimit
4,831✔
2354
                }
4,831✔
2355

2356
                return lnwallet.HtlcIsDust(
9,659✔
2357
                        chantype, incoming, whoseCommit, feerate, amt,
9,659✔
2358
                        dustLimit,
9,659✔
2359
                )
9,659✔
2360
        }
2361

2362
        return isDust
1,802✔
2363
}
2364

2365
// zeroConfConfirmed returns whether or not the zero-conf channel has
2366
// confirmed on-chain.
2367
//
2368
// Part of the scidAliasHandler interface.
2369
func (l *channelLink) zeroConfConfirmed() bool {
6✔
2370
        return l.channel.State().ZeroConfConfirmed()
6✔
2371
}
6✔
2372

2373
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
2374
// should not be called for non-zero-conf channels.
2375
//
2376
// Part of the scidAliasHandler interface.
2377
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
6✔
2378
        return l.channel.State().ZeroConfRealScid()
6✔
2379
}
6✔
2380

2381
// isZeroConf returns whether or not the underlying channel is a zero-conf
2382
// channel.
2383
//
2384
// Part of the scidAliasHandler interface.
2385
func (l *channelLink) isZeroConf() bool {
216✔
2386
        return l.channel.State().IsZeroConf()
216✔
2387
}
216✔
2388

2389
// negotiatedAliasFeature returns whether or not the underlying channel has
2390
// negotiated the option-scid-alias feature bit. This will be true for both
2391
// option-scid-alias and zero-conf channel-types. It will also be true for
2392
// channels with the feature bit but without the above channel-types.
2393
//
2394
// Part of the scidAliasFeature interface.
2395
func (l *channelLink) negotiatedAliasFeature() bool {
377✔
2396
        return l.channel.State().NegotiatedAliasFeature()
377✔
2397
}
377✔
2398

2399
// getAliases returns the set of aliases for the underlying channel.
2400
//
2401
// Part of the scidAliasHandler interface.
2402
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
222✔
2403
        return l.cfg.GetAliases(l.ShortChanID())
222✔
2404
}
222✔
2405

2406
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
2407
//
2408
// Part of the scidAliasHandler interface.
2409
func (l *channelLink) attachFailAliasUpdate(closure func(
2410
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
217✔
2411

217✔
2412
        l.Lock()
217✔
2413
        l.cfg.FailAliasUpdate = closure
217✔
2414
        l.Unlock()
217✔
2415
}
217✔
2416

2417
// AttachMailBox updates the current mailbox used by this link, and hooks up
2418
// the mailbox's message and packet outboxes to the link's upstream and
2419
// downstream chans, respectively.
2420
func (l *channelLink) AttachMailBox(mailbox MailBox) {
216✔
2421
        l.Lock()
216✔
2422
        l.mailBox = mailbox
216✔
2423
        l.upstream = mailbox.MessageOutBox()
216✔
2424
        l.downstream = mailbox.PacketOutBox()
216✔
2425
        l.Unlock()
216✔
2426

216✔
2427
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
216✔
2428
        // never committed.
216✔
2429
        l.mailBox.SetFeeRate(l.getFeeRate())
216✔
2430

216✔
2431
        // Also set the mailbox's dust closure so that it can query whether HTLC's
216✔
2432
        // are dust given the current feerate.
216✔
2433
        l.mailBox.SetDustClosure(l.getDustClosure())
216✔
2434
}
216✔
2435

2436
// UpdateForwardingPolicy updates the forwarding policy for the target
2437
// ChannelLink. Once updated, the link will use the new forwarding policy to
2438
// govern if it an incoming HTLC should be forwarded or not. We assume that
2439
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
2440
// update all of the link's FwrdingPolicy's values.
2441
//
2442
// NOTE: Part of the ChannelLink interface.
2443
func (l *channelLink) UpdateForwardingPolicy(
2444
        newPolicy models.ForwardingPolicy) {
15✔
2445

15✔
2446
        l.Lock()
15✔
2447
        defer l.Unlock()
15✔
2448

15✔
2449
        l.cfg.FwrdingPolicy = newPolicy
15✔
2450
}
15✔
2451

2452
// CheckHtlcForward should return a nil error if the passed HTLC details
2453
// satisfy the current forwarding policy fo the target link. Otherwise,
2454
// a LinkError with a valid protocol failure message should be returned
2455
// in order to signal to the source of the HTLC, the policy consistency
2456
// issue.
2457
//
2458
// NOTE: Part of the ChannelLink interface.
2459
func (l *channelLink) CheckHtlcForward(payHash [32]byte, incomingHtlcAmt,
2460
        amtToForward lnwire.MilliSatoshi, incomingTimeout,
2461
        outgoingTimeout uint32, inboundFee models.InboundFee,
2462
        heightNow uint32, originalScid lnwire.ShortChannelID,
2463
        customRecords lnwire.CustomRecords) *LinkError {
52✔
2464

52✔
2465
        l.RLock()
52✔
2466
        policy := l.cfg.FwrdingPolicy
52✔
2467
        l.RUnlock()
52✔
2468

52✔
2469
        // Using the outgoing HTLC amount, we'll calculate the outgoing
52✔
2470
        // fee this incoming HTLC must carry in order to satisfy the constraints
52✔
2471
        // of the outgoing link.
52✔
2472
        outFee := ExpectedFee(policy, amtToForward)
52✔
2473

52✔
2474
        // Then calculate the inbound fee that we charge based on the sum of
52✔
2475
        // outgoing HTLC amount and outgoing fee.
52✔
2476
        inFee := inboundFee.CalcFee(amtToForward + outFee)
52✔
2477

52✔
2478
        // Add up both fee components. It is important to calculate both fees
52✔
2479
        // separately. An alternative way of calculating is to first determine
52✔
2480
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
52✔
2481
        // rounding may cause the result to be slightly higher than in the case
52✔
2482
        // of separately rounded fee components. This potentially causes failed
52✔
2483
        // forwards for senders and is something to be avoided.
52✔
2484
        expectedFee := inFee + int64(outFee)
52✔
2485

52✔
2486
        // If the actual fee is less than our expected fee, then we'll reject
52✔
2487
        // this HTLC as it didn't provide a sufficient amount of fees, or the
52✔
2488
        // values have been tampered with, or the send used incorrect/dated
52✔
2489
        // information to construct the forwarding information for this hop. In
52✔
2490
        // any case, we'll cancel this HTLC.
52✔
2491
        actualFee := int64(incomingHtlcAmt) - int64(amtToForward)
52✔
2492
        if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
61✔
2493
                l.log.Warnf("outgoing htlc(%x) has insufficient fee: "+
9✔
2494
                        "expected %v, got %v: incoming=%v, outgoing=%v, "+
9✔
2495
                        "inboundFee=%v",
9✔
2496
                        payHash[:], expectedFee, actualFee,
9✔
2497
                        incomingHtlcAmt, amtToForward, inboundFee,
9✔
2498
                )
9✔
2499

9✔
2500
                // As part of the returned error, we'll send our latest routing
9✔
2501
                // policy so the sending node obtains the most up to date data.
9✔
2502
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
18✔
2503
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
9✔
2504
                }
9✔
2505
                failure := l.createFailureWithUpdate(false, originalScid, cb)
9✔
2506
                return NewLinkError(failure)
9✔
2507
        }
2508

2509
        // Check whether the outgoing htlc satisfies the channel policy.
2510
        err := l.canSendHtlc(
46✔
2511
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
46✔
2512
                originalScid, customRecords,
46✔
2513
        )
46✔
2514
        if err != nil {
62✔
2515
                return err
16✔
2516
        }
16✔
2517

2518
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
2519
        // the following constraint: the incoming time-lock minus our time-lock
2520
        // delta should equal the outgoing time lock. Otherwise, whether the
2521
        // sender messed up, or an intermediate node tampered with the HTLC.
2522
        timeDelta := policy.TimeLockDelta
33✔
2523
        if incomingTimeout < outgoingTimeout+timeDelta {
35✔
2524
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
2✔
2525
                        "expected at least %v block delta, got %v block delta",
2✔
2526
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
2✔
2527

2✔
2528
                // Grab the latest routing policy so the sending node is up to
2✔
2529
                // date with our current policy.
2✔
2530
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
2531
                        return lnwire.NewIncorrectCltvExpiry(
2✔
2532
                                incomingTimeout, *upd,
2✔
2533
                        )
2✔
2534
                }
2✔
2535
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
2536
                return NewLinkError(failure)
2✔
2537
        }
2538

2539
        return nil
31✔
2540
}
2541

2542
// CheckHtlcTransit should return a nil error if the passed HTLC details
2543
// satisfy the current channel policy.  Otherwise, a LinkError with a
2544
// valid protocol failure message should be returned in order to signal
2545
// the violation. This call is intended to be used for locally initiated
2546
// payments for which there is no corresponding incoming htlc.
2547
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
2548
        amt lnwire.MilliSatoshi, timeout uint32, heightNow uint32,
2549
        customRecords lnwire.CustomRecords) *LinkError {
409✔
2550

409✔
2551
        l.RLock()
409✔
2552
        policy := l.cfg.FwrdingPolicy
409✔
2553
        l.RUnlock()
409✔
2554

409✔
2555
        // We pass in hop.Source here as this is only used in the Switch when
409✔
2556
        // trying to send over a local link. This causes the fallback mechanism
409✔
2557
        // to occur.
409✔
2558
        return l.canSendHtlc(
409✔
2559
                policy, payHash, amt, timeout, heightNow, hop.Source,
409✔
2560
                customRecords,
409✔
2561
        )
409✔
2562
}
409✔
2563

2564
// canSendHtlc checks whether the given htlc parameters satisfy
2565
// the channel's amount and time lock constraints.
2566
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
2567
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
2568
        heightNow uint32, originalScid lnwire.ShortChannelID,
2569
        customRecords lnwire.CustomRecords) *LinkError {
452✔
2570

452✔
2571
        // Validate HTLC amount against policy limits.
452✔
2572
        linkErr := l.validateHtlcAmount(
452✔
2573
                policy, payHash, amt, originalScid, customRecords,
452✔
2574
        )
452✔
2575
        if linkErr != nil {
466✔
2576
                return linkErr
14✔
2577
        }
14✔
2578

2579
        // We want to avoid offering an HTLC which will expire in the near
2580
        // future, so we'll reject an HTLC if the outgoing expiration time is
2581
        // too close to the current height.
2582
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
443✔
2583
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
2✔
2584
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
2✔
2585
                        timeout, heightNow)
2✔
2586

2✔
2587
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
2588
                        return lnwire.NewExpiryTooSoon(*upd)
2✔
2589
                }
2✔
2590
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
2591

2✔
2592
                return NewLinkError(failure)
2✔
2593
        }
2594

2595
        // Check absolute max delta.
2596
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
440✔
2597
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
1✔
2598
                        "the future: got %v, but maximum is %v", payHash[:],
1✔
2599
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
1✔
2600

1✔
2601
                return NewLinkError(&lnwire.FailExpiryTooFar{})
1✔
2602
        }
1✔
2603

2604
        // We now check the available bandwidth to see if this HTLC can be
2605
        // forwarded.
2606
        availableBandwidth := l.Bandwidth()
438✔
2607

438✔
2608
        auxBandwidth, externalErr := fn.MapOptionZ(
438✔
2609
                l.cfg.AuxTrafficShaper,
438✔
2610
                func(ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
438✔
2611
                        var htlcBlob fn.Option[tlv.Blob]
×
2612
                        blob, err := customRecords.Serialize()
×
2613
                        if err != nil {
×
2614
                                return fn.Err[OptionalBandwidth](
×
2615
                                        fmt.Errorf("unable to serialize "+
×
2616
                                                "custom records: %w", err))
×
2617
                        }
×
2618

2619
                        if len(blob) > 0 {
×
2620
                                htlcBlob = fn.Some(blob)
×
2621
                        }
×
2622

2623
                        return l.AuxBandwidth(amt, originalScid, htlcBlob, ts)
×
2624
                },
2625
        ).Unpack()
2626
        if externalErr != nil {
438✔
2627
                l.log.Errorf("Unable to determine aux bandwidth: %v",
×
2628
                        externalErr)
×
2629

×
2630
                return NewLinkError(&lnwire.FailTemporaryNodeFailure{})
×
2631
        }
×
2632

2633
        if auxBandwidth.IsHandled && auxBandwidth.Bandwidth.IsSome() {
438✔
2634
                auxBandwidth.Bandwidth.WhenSome(
×
2635
                        func(bandwidth lnwire.MilliSatoshi) {
×
2636
                                availableBandwidth = bandwidth
×
2637
                        },
×
2638
                )
2639
        }
2640

2641
        // Check to see if there is enough balance in this channel.
2642
        if amt > availableBandwidth {
442✔
2643
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
4✔
2644
                        "larger than %v", amt, availableBandwidth)
4✔
2645
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
2646
                        return lnwire.NewTemporaryChannelFailure(upd)
4✔
2647
                }
4✔
2648
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
2649

4✔
2650
                return NewDetailedLinkError(
4✔
2651
                        failure, OutgoingFailureInsufficientBalance,
4✔
2652
                )
4✔
2653
        }
2654

2655
        return nil
437✔
2656
}
2657

2658
// AuxBandwidth returns the bandwidth that can be used for a channel, expressed
2659
// in milli-satoshi. This might be different from the regular BTC bandwidth for
2660
// custom channels. This will always return fn.None() for a regular (non-custom)
2661
// channel.
2662
func (l *channelLink) AuxBandwidth(amount lnwire.MilliSatoshi,
2663
        cid lnwire.ShortChannelID, htlcBlob fn.Option[tlv.Blob],
2664
        ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
×
2665

×
2666
        fundingBlob := l.FundingCustomBlob()
×
2667
        shouldHandle, err := ts.ShouldHandleTraffic(cid, fundingBlob, htlcBlob)
×
2668
        if err != nil {
×
2669
                return fn.Err[OptionalBandwidth](fmt.Errorf("traffic shaper "+
×
2670
                        "failed to decide whether to handle traffic: %w", err))
×
2671
        }
×
2672

2673
        log.Debugf("ShortChannelID=%v: aux traffic shaper is handling "+
×
2674
                "traffic: %v", cid, shouldHandle)
×
2675

×
2676
        // If this channel isn't handled by the aux traffic shaper, we'll return
×
2677
        // early.
×
2678
        if !shouldHandle {
×
2679
                return fn.Ok(OptionalBandwidth{
×
2680
                        IsHandled: false,
×
2681
                })
×
2682
        }
×
2683

2684
        peerBytes := l.cfg.Peer.PubKey()
×
2685

×
2686
        peer, err := route.NewVertexFromBytes(peerBytes[:])
×
2687
        if err != nil {
×
2688
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to decode "+
×
2689
                        "peer pub key: %v", err))
×
2690
        }
×
2691

2692
        // Ask for a specific bandwidth to be used for the channel.
2693
        commitmentBlob := l.CommitmentCustomBlob()
×
2694
        auxBandwidth, err := ts.PaymentBandwidth(
×
2695
                fundingBlob, htlcBlob, commitmentBlob, l.Bandwidth(), amount,
×
2696
                l.channel.FetchLatestAuxHTLCView(), peer,
×
2697
        )
×
2698
        if err != nil {
×
2699
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to get "+
×
2700
                        "bandwidth from external traffic shaper: %w", err))
×
2701
        }
×
2702

2703
        log.Debugf("ShortChannelID=%v: aux traffic shaper reported available "+
×
2704
                "bandwidth: %v", cid, auxBandwidth)
×
2705

×
2706
        return fn.Ok(OptionalBandwidth{
×
2707
                IsHandled: true,
×
2708
                Bandwidth: fn.Some(auxBandwidth),
×
2709
        })
×
2710
}
2711

2712
// Stats returns the statistics of channel link.
2713
//
2714
// NOTE: Part of the ChannelLink interface.
2715
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
7✔
2716
        snapshot := l.channel.StateSnapshot()
7✔
2717

7✔
2718
        return snapshot.ChannelCommitment.CommitHeight,
7✔
2719
                snapshot.TotalMSatSent,
7✔
2720
                snapshot.TotalMSatReceived
7✔
2721
}
7✔
2722

2723
// String returns the string representation of channel link.
2724
//
2725
// NOTE: Part of the ChannelLink interface.
2726
func (l *channelLink) String() string {
×
2727
        return l.channel.ChannelPoint().String()
×
2728
}
×
2729

2730
// handleSwitchPacket handles the switch packets. This packets which might be
2731
// forwarded to us from another channel link in case the htlc update came from
2732
// another peer or if the update was created by user
2733
//
2734
// NOTE: Part of the packetHandler interface.
2735
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
482✔
2736
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
482✔
2737
                pkt.inKey(), pkt.outKey())
482✔
2738

482✔
2739
        return l.mailBox.AddPacket(pkt)
482✔
2740
}
482✔
2741

2742
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
2743
// to us from remote peer we have a channel with.
2744
//
2745
// NOTE: Part of the ChannelLink interface.
2746
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
3,399✔
2747
        select {
3,399✔
2748
        case <-l.cg.Done():
×
2749
                // Return early if the link is already in the process of
×
2750
                // quitting. It doesn't make sense to hand the message to the
×
2751
                // mailbox here.
×
2752
                return
×
2753
        default:
3,399✔
2754
        }
2755

2756
        err := l.mailBox.AddMessage(message)
3,399✔
2757
        if err != nil {
3,399✔
2758
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
2759
        }
×
2760
}
2761

2762
// updateChannelFee updates the commitment fee-per-kw on this channel by
2763
// committing to an update_fee message.
2764
func (l *channelLink) updateChannelFee(ctx context.Context,
2765
        feePerKw chainfee.SatPerKWeight) error {
3✔
2766

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

3✔
2769
        // We skip sending the UpdateFee message if the channel is not
3✔
2770
        // currently eligible to forward messages.
3✔
2771
        if !l.eligibleToUpdate() {
3✔
2772
                l.log.Debugf("skipping fee update for inactive channel")
×
2773
                return nil
×
2774
        }
×
2775

2776
        // Check and see if our proposed fee-rate would make us exceed the fee
2777
        // threshold.
2778
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
3✔
2779
        if err != nil {
3✔
2780
                // This shouldn't typically happen. If it does, it indicates
×
2781
                // something is wrong with our channel state.
×
2782
                return err
×
2783
        }
×
2784

2785
        if thresholdExceeded {
3✔
2786
                return fmt.Errorf("link fee threshold exceeded")
×
2787
        }
×
2788

2789
        // First, we'll update the local fee on our commitment.
2790
        if err := l.channel.UpdateFee(feePerKw); err != nil {
3✔
2791
                return err
×
2792
        }
×
2793

2794
        // The fee passed the channel's validation checks, so we update the
2795
        // mailbox feerate.
2796
        l.mailBox.SetFeeRate(feePerKw)
3✔
2797

3✔
2798
        // We'll then attempt to send a new UpdateFee message, and also lock it
3✔
2799
        // in immediately by triggering a commitment update.
3✔
2800
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
3✔
2801
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
2802
                return err
×
2803
        }
×
2804

2805
        return l.updateCommitTx(ctx)
3✔
2806
}
2807

2808
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
2809
// after receiving a revocation from the remote party, and reprocesses them in
2810
// the context of the provided forwarding package. Any settles or fails that
2811
// have already been acknowledged in the forwarding package will not be sent to
2812
// the switch.
2813
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
1,205✔
2814
        if len(fwdPkg.SettleFails) == 0 {
2,096✔
2815
                l.log.Trace("fwd package has no settle/fails to process " +
891✔
2816
                        "exiting early")
891✔
2817

891✔
2818
                return
891✔
2819
        }
891✔
2820

2821
        // Exit early if the fwdPkg is already processed.
2822
        if fwdPkg.State == channeldb.FwdStateCompleted {
317✔
2823
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
2824

×
2825
                return
×
2826
        }
×
2827

2828
        l.log.Debugf("settle-fail-filter: %v", fwdPkg.SettleFailFilter)
317✔
2829

317✔
2830
        var switchPackets []*htlcPacket
317✔
2831
        for i, update := range fwdPkg.SettleFails {
634✔
2832
                destRef := fwdPkg.DestRef(uint16(i))
317✔
2833

317✔
2834
                // Skip any settles or fails that have already been
317✔
2835
                // acknowledged by the incoming link that originated the
317✔
2836
                // forwarded Add.
317✔
2837
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
317✔
2838
                        continue
×
2839
                }
2840

2841
                // TODO(roasbeef): rework log entries to a shared
2842
                // interface.
2843

2844
                switch msg := update.UpdateMsg.(type) {
317✔
2845
                // A settle for an HTLC we previously forwarded HTLC has been
2846
                // received. So we'll forward the HTLC to the switch which will
2847
                // handle propagating the settle to the prior hop.
2848
                case *lnwire.UpdateFulfillHTLC:
194✔
2849
                        // If hodl.SettleIncoming is requested, we will not
194✔
2850
                        // forward the SETTLE to the switch and will not signal
194✔
2851
                        // a free slot on the commitment transaction.
194✔
2852
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
194✔
2853
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
2854
                                continue
×
2855
                        }
2856

2857
                        settlePacket := &htlcPacket{
194✔
2858
                                outgoingChanID: l.ShortChanID(),
194✔
2859
                                outgoingHTLCID: msg.ID,
194✔
2860
                                destRef:        &destRef,
194✔
2861
                                htlc:           msg,
194✔
2862
                        }
194✔
2863

194✔
2864
                        // Add the packet to the batch to be forwarded, and
194✔
2865
                        // notify the overflow queue that a spare spot has been
194✔
2866
                        // freed up within the commitment state.
194✔
2867
                        switchPackets = append(switchPackets, settlePacket)
194✔
2868

2869
                // A failureCode message for a previously forwarded HTLC has
2870
                // been received. As a result a new slot will be freed up in
2871
                // our commitment state, so we'll forward this to the switch so
2872
                // the backwards undo can continue.
2873
                case *lnwire.UpdateFailHTLC:
126✔
2874
                        // If hodl.SettleIncoming is requested, we will not
126✔
2875
                        // forward the FAIL to the switch and will not signal a
126✔
2876
                        // free slot on the commitment transaction.
126✔
2877
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
126✔
2878
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
2879
                                continue
×
2880
                        }
2881

2882
                        // Fetch the reason the HTLC was canceled so we can
2883
                        // continue to propagate it. This failure originated
2884
                        // from another node, so the linkFailure field is not
2885
                        // set on the packet.
2886
                        failPacket := &htlcPacket{
126✔
2887
                                outgoingChanID: l.ShortChanID(),
126✔
2888
                                outgoingHTLCID: msg.ID,
126✔
2889
                                destRef:        &destRef,
126✔
2890
                                htlc:           msg,
126✔
2891
                        }
126✔
2892

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

126✔
2895
                        // If the failure message lacks an HMAC (but includes
126✔
2896
                        // the 4 bytes for encoding the message and padding
126✔
2897
                        // lengths, then this means that we received it as an
126✔
2898
                        // UpdateFailMalformedHTLC. As a result, we'll signal
126✔
2899
                        // that we need to convert this error within the switch
126✔
2900
                        // to an actual error, by encrypting it as if we were
126✔
2901
                        // the originating hop.
126✔
2902
                        convertedErrorSize := lnwire.FailureMessageLength + 4
126✔
2903
                        if len(msg.Reason) == convertedErrorSize {
132✔
2904
                                failPacket.convertedError = true
6✔
2905
                        }
6✔
2906

2907
                        // Add the packet to the batch to be forwarded, and
2908
                        // notify the overflow queue that a spare spot has been
2909
                        // freed up within the commitment state.
2910
                        switchPackets = append(switchPackets, failPacket)
126✔
2911
                }
2912
        }
2913

2914
        // Only spawn the task forward packets we have a non-zero number.
2915
        if len(switchPackets) > 0 {
634✔
2916
                go l.forwardBatch(false, switchPackets...)
317✔
2917
        }
317✔
2918
}
2919

2920
// processRemoteAdds serially processes each of the Add payment descriptors
2921
// which have been "locked-in" by receiving a revocation from the remote party.
2922
// The forwarding package provided instructs how to process this batch,
2923
// indicating whether this is the first time these Adds are being processed, or
2924
// whether we are reprocessing as a result of a failure or restart. Adds that
2925
// have already been acknowledged in the forwarding package will be ignored.
2926
//
2927
// NOTE: This function needs also be called for fwd packages with no ADDs
2928
// because it marks the fwdPkg as processed by writing the FwdFilter into the
2929
// database.
2930
//
2931
//nolint:funlen
2932
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
1,207✔
2933
        // Exit early if the fwdPkg is already processed.
1,207✔
2934
        if fwdPkg.State == channeldb.FwdStateCompleted {
1,207✔
2935
                l.log.Debugf("skipped processing completed fwdPkg %v", fwdPkg)
×
2936

×
2937
                return
×
2938
        }
×
2939

2940
        l.log.Tracef("processing %d remote adds for height %d",
1,207✔
2941
                len(fwdPkg.Adds), fwdPkg.Height)
1,207✔
2942

1,207✔
2943
        // decodeReqs is a list of requests sent to the onion decoder. We expect
1,207✔
2944
        // the same length of responses to be returned.
1,207✔
2945
        decodeReqs := make([]hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds))
1,207✔
2946

1,207✔
2947
        // unackedAdds is a list of ADDs that's waiting for the remote's
1,207✔
2948
        // settle/fail update.
1,207✔
2949
        unackedAdds := make([]*lnwire.UpdateAddHTLC, 0, len(fwdPkg.Adds))
1,207✔
2950

1,207✔
2951
        for i, update := range fwdPkg.Adds {
1,659✔
2952
                // If this index is already found in the ack filter, the
452✔
2953
                // response to this forwarding decision has already been
452✔
2954
                // committed by one of our commitment txns. ADDs in this state
452✔
2955
                // are waiting for the rest of the fwding package to get acked
452✔
2956
                // before being garbage collected.
452✔
2957
                if fwdPkg.State == channeldb.FwdStateProcessed &&
452✔
2958
                        fwdPkg.AckFilter.Contains(uint16(i)) {
452✔
2959

×
2960
                        continue
×
2961
                }
2962

2963
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
904✔
2964
                        // Before adding the new htlc to the state machine,
452✔
2965
                        // parse the onion object in order to obtain the
452✔
2966
                        // routing information with DecodeHopIterator function
452✔
2967
                        // which process the Sphinx packet.
452✔
2968
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
452✔
2969

452✔
2970
                        req := hop.DecodeHopIteratorRequest{
452✔
2971
                                OnionReader:    onionReader,
452✔
2972
                                RHash:          msg.PaymentHash[:],
452✔
2973
                                IncomingCltv:   msg.Expiry,
452✔
2974
                                IncomingAmount: msg.Amount,
452✔
2975
                                BlindingPoint:  msg.BlindingPoint,
452✔
2976
                        }
452✔
2977

452✔
2978
                        decodeReqs = append(decodeReqs, req)
452✔
2979
                        unackedAdds = append(unackedAdds, msg)
452✔
2980
                }
452✔
2981
        }
2982

2983
        // If the fwdPkg has already been processed, it means we are
2984
        // reforwarding the packets again, which happens only on a restart.
2985
        reforward := fwdPkg.State == channeldb.FwdStateProcessed
1,207✔
2986

1,207✔
2987
        // Atomically decode the incoming htlcs, simultaneously checking for
1,207✔
2988
        // replay attempts. A particular index in the returned, spare list of
1,207✔
2989
        // channel iterators should only be used if the failure code at the
1,207✔
2990
        // same index is lnwire.FailCodeNone.
1,207✔
2991
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
1,207✔
2992
                fwdPkg.ID(), decodeReqs, reforward,
1,207✔
2993
        )
1,207✔
2994
        if sphinxErr != nil {
1,207✔
2995
                l.failf(LinkFailureError{code: ErrInternalError},
×
2996
                        "unable to decode hop iterators: %v", sphinxErr)
×
2997
                return
×
2998
        }
×
2999

3000
        var switchPackets []*htlcPacket
1,207✔
3001

1,207✔
3002
        for i, update := range unackedAdds {
1,659✔
3003
                idx := uint16(i)
452✔
3004
                sourceRef := fwdPkg.SourceRef(idx)
452✔
3005
                add := *update
452✔
3006

452✔
3007
                // An incoming HTLC add has been full-locked in. As a result we
452✔
3008
                // can now examine the forwarding details of the HTLC, and the
452✔
3009
                // HTLC itself to decide if: we should forward it, cancel it,
452✔
3010
                // or are able to settle it (and it adheres to our fee related
452✔
3011
                // constraints).
452✔
3012

452✔
3013
                // Before adding the new htlc to the state machine, parse the
452✔
3014
                // onion object in order to obtain the routing information with
452✔
3015
                // DecodeHopIterator function which process the Sphinx packet.
452✔
3016
                chanIterator, failureCode := decodeResps[i].Result()
452✔
3017
                if failureCode != lnwire.CodeNone {
457✔
3018
                        // If we're unable to process the onion blob then we
5✔
3019
                        // should send the malformed htlc error to payment
5✔
3020
                        // sender.
5✔
3021
                        l.sendMalformedHTLCError(
5✔
3022
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
5✔
3023
                        )
5✔
3024

5✔
3025
                        l.log.Errorf("unable to decode onion hop iterator "+
5✔
3026
                                "for htlc(id=%v, hash=%x): %v", add.ID,
5✔
3027
                                add.PaymentHash, failureCode)
5✔
3028

5✔
3029
                        continue
5✔
3030
                }
3031

3032
                heightNow := l.cfg.BestHeight()
450✔
3033

450✔
3034
                pld, routeRole, pldErr := chanIterator.HopPayload()
450✔
3035
                if pldErr != nil {
453✔
3036
                        // If we're unable to process the onion payload, or we
3✔
3037
                        // received invalid onion payload failure, then we
3✔
3038
                        // should send an error back to the caller so the HTLC
3✔
3039
                        // can be canceled.
3✔
3040
                        var failedType uint64
3✔
3041

3✔
3042
                        // We need to get the underlying error value, so we
3✔
3043
                        // can't use errors.As as suggested by the linter.
3✔
3044
                        //nolint:errorlint
3✔
3045
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
3✔
3046
                                failedType = uint64(e.Type)
×
3047
                        }
×
3048

3049
                        // If we couldn't parse the payload, make our best
3050
                        // effort at creating an error encrypter that knows
3051
                        // what blinding type we were, but if we couldn't
3052
                        // parse the payload we have no way of knowing whether
3053
                        // we were the introduction node or not.
3054
                        //
3055
                        //nolint:ll
3056
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
3✔
3057
                                l.cfg.ExtractErrorEncrypter,
3✔
3058
                                // We need our route role here because we
3✔
3059
                                // couldn't parse or validate the payload.
3✔
3060
                                routeRole == hop.RouteRoleIntroduction,
3✔
3061
                        )
3✔
3062
                        if failCode != lnwire.CodeNone {
3✔
3063
                                l.log.Errorf("could not extract error "+
×
3064
                                        "encrypter: %v", pldErr)
×
3065

×
3066
                                // We can't process this htlc, send back
×
3067
                                // malformed.
×
3068
                                l.sendMalformedHTLCError(
×
3069
                                        add.ID, failureCode, add.OnionBlob,
×
3070
                                        &sourceRef,
×
3071
                                )
×
3072

×
3073
                                continue
×
3074
                        }
3075

3076
                        // TODO: currently none of the test unit infrastructure
3077
                        // is setup to handle TLV payloads, so testing this
3078
                        // would require implementing a separate mock iterator
3079
                        // for TLV payloads that also supports injecting invalid
3080
                        // payloads. Deferring this non-trival effort till a
3081
                        // later date
3082
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
3✔
3083

3✔
3084
                        l.sendHTLCError(
3✔
3085
                                add, sourceRef, NewLinkError(failure),
3✔
3086
                                obfuscator, false,
3✔
3087
                        )
3✔
3088

3✔
3089
                        l.log.Errorf("unable to decode forwarding "+
3✔
3090
                                "instructions: %v", pldErr)
3✔
3091

3✔
3092
                        continue
3✔
3093
                }
3094

3095
                // Retrieve onion obfuscator from onion blob in order to
3096
                // produce initial obfuscation of the onion failureCode.
3097
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
450✔
3098
                        l.cfg.ExtractErrorEncrypter,
450✔
3099
                        routeRole == hop.RouteRoleIntroduction,
450✔
3100
                )
450✔
3101
                if failureCode != lnwire.CodeNone {
451✔
3102
                        // If we're unable to process the onion blob than we
1✔
3103
                        // should send the malformed htlc error to payment
1✔
3104
                        // sender.
1✔
3105
                        l.sendMalformedHTLCError(
1✔
3106
                                add.ID, failureCode, add.OnionBlob,
1✔
3107
                                &sourceRef,
1✔
3108
                        )
1✔
3109

1✔
3110
                        l.log.Errorf("unable to decode onion "+
1✔
3111
                                "obfuscator: %v", failureCode)
1✔
3112

1✔
3113
                        continue
1✔
3114
                }
3115

3116
                fwdInfo := pld.ForwardingInfo()
449✔
3117

449✔
3118
                // Check whether the payload we've just processed uses our
449✔
3119
                // node as the introduction point (gave us a blinding key in
449✔
3120
                // the payload itself) and fail it back if we don't support
449✔
3121
                // route blinding.
449✔
3122
                if fwdInfo.NextBlinding.IsSome() &&
449✔
3123
                        l.cfg.DisallowRouteBlinding {
452✔
3124

3✔
3125
                        failure := lnwire.NewInvalidBlinding(
3✔
3126
                                fn.Some(add.OnionBlob),
3✔
3127
                        )
3✔
3128

3✔
3129
                        l.sendHTLCError(
3✔
3130
                                add, sourceRef, NewLinkError(failure),
3✔
3131
                                obfuscator, false,
3✔
3132
                        )
3✔
3133

3✔
3134
                        l.log.Error("rejected htlc that uses use as an " +
3✔
3135
                                "introduction point when we do not support " +
3✔
3136
                                "route blinding")
3✔
3137

3✔
3138
                        continue
3✔
3139
                }
3140

3141
                switch fwdInfo.NextHop {
449✔
3142
                case hop.Exit:
413✔
3143
                        err := l.processExitHop(
413✔
3144
                                add, sourceRef, obfuscator, fwdInfo,
413✔
3145
                                heightNow, pld,
413✔
3146
                        )
413✔
3147
                        if err != nil {
413✔
3148
                                l.failf(LinkFailureError{
×
3149
                                        code: ErrInternalError,
×
3150
                                }, "%v", err)
×
3151

×
3152
                                return
×
3153
                        }
×
3154

3155
                // There are additional channels left within this route. So
3156
                // we'll simply do some forwarding package book-keeping.
3157
                default:
39✔
3158
                        // If hodl.AddIncoming is requested, we will not
39✔
3159
                        // validate the forwarded ADD, nor will we send the
39✔
3160
                        // packet to the htlc switch.
39✔
3161
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
39✔
3162
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3163
                                continue
×
3164
                        }
3165

3166
                        endorseValue := l.experimentalEndorsement(
39✔
3167
                                record.CustomSet(add.CustomRecords),
39✔
3168
                        )
39✔
3169
                        endorseType := uint64(
39✔
3170
                                lnwire.ExperimentalEndorsementType,
39✔
3171
                        )
39✔
3172

39✔
3173
                        switch fwdPkg.State {
39✔
3174
                        case channeldb.FwdStateProcessed:
3✔
3175
                                // This add was not forwarded on the previous
3✔
3176
                                // processing phase, run it through our
3✔
3177
                                // validation pipeline to reproduce an error.
3✔
3178
                                // This may trigger a different error due to
3✔
3179
                                // expiring timelocks, but we expect that an
3✔
3180
                                // error will be reproduced.
3✔
3181
                                if !fwdPkg.FwdFilter.Contains(idx) {
3✔
3182
                                        break
×
3183
                                }
3184

3185
                                // Otherwise, it was already processed, we can
3186
                                // can collect it and continue.
3187
                                outgoingAdd := &lnwire.UpdateAddHTLC{
3✔
3188
                                        Expiry:        fwdInfo.OutgoingCTLV,
3✔
3189
                                        Amount:        fwdInfo.AmountToForward,
3✔
3190
                                        PaymentHash:   add.PaymentHash,
3✔
3191
                                        BlindingPoint: fwdInfo.NextBlinding,
3✔
3192
                                }
3✔
3193

3✔
3194
                                endorseValue.WhenSome(func(e byte) {
6✔
3195
                                        custRecords := map[uint64][]byte{
3✔
3196
                                                endorseType: {e},
3✔
3197
                                        }
3✔
3198

3✔
3199
                                        outgoingAdd.CustomRecords = custRecords
3✔
3200
                                })
3✔
3201

3202
                                // Finally, we'll encode the onion packet for
3203
                                // the _next_ hop using the hop iterator
3204
                                // decoded for the current hop.
3205
                                buf := bytes.NewBuffer(
3✔
3206
                                        outgoingAdd.OnionBlob[0:0],
3✔
3207
                                )
3✔
3208

3✔
3209
                                // We know this cannot fail, as this ADD
3✔
3210
                                // was marked forwarded in a previous
3✔
3211
                                // round of processing.
3✔
3212
                                chanIterator.EncodeNextHop(buf)
3✔
3213

3✔
3214
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
3✔
3215

3✔
3216
                                //nolint:ll
3✔
3217
                                updatePacket := &htlcPacket{
3✔
3218
                                        incomingChanID:       l.ShortChanID(),
3✔
3219
                                        incomingHTLCID:       add.ID,
3✔
3220
                                        outgoingChanID:       fwdInfo.NextHop,
3✔
3221
                                        sourceRef:            &sourceRef,
3✔
3222
                                        incomingAmount:       add.Amount,
3✔
3223
                                        amount:               outgoingAdd.Amount,
3✔
3224
                                        htlc:                 outgoingAdd,
3✔
3225
                                        obfuscator:           obfuscator,
3✔
3226
                                        incomingTimeout:      add.Expiry,
3✔
3227
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
3✔
3228
                                        inOnionCustomRecords: pld.CustomRecords(),
3✔
3229
                                        inboundFee:           inboundFee,
3✔
3230
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
3✔
3231
                                }
3✔
3232
                                switchPackets = append(
3✔
3233
                                        switchPackets, updatePacket,
3✔
3234
                                )
3✔
3235

3✔
3236
                                continue
3✔
3237
                        }
3238

3239
                        // TODO(roasbeef): ensure don't accept outrageous
3240
                        // timeout for htlc
3241

3242
                        // With all our forwarding constraints met, we'll
3243
                        // create the outgoing HTLC using the parameters as
3244
                        // specified in the forwarding info.
3245
                        addMsg := &lnwire.UpdateAddHTLC{
39✔
3246
                                Expiry:        fwdInfo.OutgoingCTLV,
39✔
3247
                                Amount:        fwdInfo.AmountToForward,
39✔
3248
                                PaymentHash:   add.PaymentHash,
39✔
3249
                                BlindingPoint: fwdInfo.NextBlinding,
39✔
3250
                        }
39✔
3251

39✔
3252
                        endorseValue.WhenSome(func(e byte) {
78✔
3253
                                addMsg.CustomRecords = map[uint64][]byte{
39✔
3254
                                        endorseType: {e},
39✔
3255
                                }
39✔
3256
                        })
39✔
3257

3258
                        // Finally, we'll encode the onion packet for the
3259
                        // _next_ hop using the hop iterator decoded for the
3260
                        // current hop.
3261
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
39✔
3262
                        err := chanIterator.EncodeNextHop(buf)
39✔
3263
                        if err != nil {
39✔
3264
                                l.log.Errorf("unable to encode the "+
×
3265
                                        "remaining route %v", err)
×
3266

×
3267
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
3268
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
3269
                                }
×
3270

3271
                                failure := l.createFailureWithUpdate(
×
3272
                                        true, hop.Source, cb,
×
3273
                                )
×
3274

×
3275
                                l.sendHTLCError(
×
3276
                                        add, sourceRef, NewLinkError(failure),
×
3277
                                        obfuscator, false,
×
3278
                                )
×
3279
                                continue
×
3280
                        }
3281

3282
                        // Now that this add has been reprocessed, only append
3283
                        // it to our list of packets to forward to the switch
3284
                        // this is the first time processing the add. If the
3285
                        // fwd pkg has already been processed, then we entered
3286
                        // the above section to recreate a previous error.  If
3287
                        // the packet had previously been forwarded, it would
3288
                        // have been added to switchPackets at the top of this
3289
                        // section.
3290
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
78✔
3291
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
39✔
3292

39✔
3293
                                //nolint:ll
39✔
3294
                                updatePacket := &htlcPacket{
39✔
3295
                                        incomingChanID:       l.ShortChanID(),
39✔
3296
                                        incomingHTLCID:       add.ID,
39✔
3297
                                        outgoingChanID:       fwdInfo.NextHop,
39✔
3298
                                        sourceRef:            &sourceRef,
39✔
3299
                                        incomingAmount:       add.Amount,
39✔
3300
                                        amount:               addMsg.Amount,
39✔
3301
                                        htlc:                 addMsg,
39✔
3302
                                        obfuscator:           obfuscator,
39✔
3303
                                        incomingTimeout:      add.Expiry,
39✔
3304
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
39✔
3305
                                        inOnionCustomRecords: pld.CustomRecords(),
39✔
3306
                                        inboundFee:           inboundFee,
39✔
3307
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
39✔
3308
                                }
39✔
3309

39✔
3310
                                fwdPkg.FwdFilter.Set(idx)
39✔
3311
                                switchPackets = append(switchPackets,
39✔
3312
                                        updatePacket)
39✔
3313
                        }
39✔
3314
                }
3315
        }
3316

3317
        // Commit the htlcs we are intending to forward if this package has not
3318
        // been fully processed.
3319
        if fwdPkg.State == channeldb.FwdStateLockedIn {
2,411✔
3320
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
1,204✔
3321
                if err != nil {
1,204✔
3322
                        l.failf(LinkFailureError{code: ErrInternalError},
×
3323
                                "unable to set fwd filter: %v", err)
×
3324
                        return
×
3325
                }
×
3326
        }
3327

3328
        if len(switchPackets) == 0 {
2,378✔
3329
                return
1,171✔
3330
        }
1,171✔
3331

3332
        l.log.Debugf("forwarding %d packets to switch: reforward=%v",
39✔
3333
                len(switchPackets), reforward)
39✔
3334

39✔
3335
        // NOTE: This call is made synchronous so that we ensure all circuits
39✔
3336
        // are committed in the exact order that they are processed in the link.
39✔
3337
        // Failing to do this could cause reorderings/gaps in the range of
39✔
3338
        // opened circuits, which violates assumptions made by the circuit
39✔
3339
        // trimming.
39✔
3340
        l.forwardBatch(reforward, switchPackets...)
39✔
3341
}
3342

3343
// experimentalEndorsement returns the value to set for our outgoing
3344
// experimental endorsement field, and a boolean indicating whether it should
3345
// be populated on the outgoing htlc.
3346
func (l *channelLink) experimentalEndorsement(
3347
        customUpdateAdd record.CustomSet) fn.Option[byte] {
39✔
3348

39✔
3349
        // Only relay experimental signal if we are within the experiment
39✔
3350
        // period.
39✔
3351
        if !l.cfg.ShouldFwdExpEndorsement() {
42✔
3352
                return fn.None[byte]()
3✔
3353
        }
3✔
3354

3355
        // If we don't have any custom records or the experimental field is
3356
        // not set, just forward a zero value.
3357
        if len(customUpdateAdd) == 0 {
78✔
3358
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
39✔
3359
        }
39✔
3360

3361
        t := uint64(lnwire.ExperimentalEndorsementType)
3✔
3362
        value, set := customUpdateAdd[t]
3✔
3363
        if !set {
3✔
3364
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
3365
        }
×
3366

3367
        // We expect at least one byte for this field, consider it invalid if
3368
        // it has no data and just forward a zero value.
3369
        if len(value) == 0 {
3✔
3370
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
3371
        }
×
3372

3373
        // Only forward endorsed if the incoming link is endorsed.
3374
        if value[0] == lnwire.ExperimentalEndorsed {
6✔
3375
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
3✔
3376
        }
3✔
3377

3378
        // Forward as unendorsed otherwise, including cases where we've
3379
        // received an invalid value that uses more than 3 bits of information.
3380
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
3✔
3381
}
3382

3383
// processExitHop handles an htlc for which this link is the exit hop. It
3384
// returns a boolean indicating whether the commitment tx needs an update.
3385
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
3386
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
3387
        fwdInfo hop.ForwardingInfo, heightNow uint32,
3388
        payload invoices.Payload) error {
413✔
3389

413✔
3390
        // If hodl.ExitSettle is requested, we will not validate the final hop's
413✔
3391
        // ADD, nor will we settle the corresponding invoice or respond with the
413✔
3392
        // preimage.
413✔
3393
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
523✔
3394
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
110✔
3395
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
110✔
3396

110✔
3397
                return nil
110✔
3398
        }
110✔
3399

3400
        // In case the traffic shaper is active, we'll check if the HTLC has
3401
        // custom records and skip the amount check in the onion payload below.
3402
        isCustomHTLC := fn.MapOptionZ(
306✔
3403
                l.cfg.AuxTrafficShaper,
306✔
3404
                func(ts AuxTrafficShaper) bool {
306✔
3405
                        return ts.IsCustomHTLC(add.CustomRecords)
×
3406
                },
×
3407
        )
3408

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

100✔
3418
                failure := NewLinkError(
100✔
3419
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
100✔
3420
                )
100✔
3421
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
100✔
3422

100✔
3423
                return nil
100✔
3424
        }
100✔
3425

3426
        // We'll also ensure that our time-lock value has been computed
3427
        // correctly.
3428
        if add.Expiry < fwdInfo.OutgoingCTLV {
207✔
3429
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
1✔
3430
                        "incompatible time-lock: expected <=%v, got %v",
1✔
3431
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
1✔
3432

1✔
3433
                failure := NewLinkError(
1✔
3434
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
1✔
3435
                )
1✔
3436

1✔
3437
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
1✔
3438

1✔
3439
                return nil
1✔
3440
        }
1✔
3441

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

205✔
3447
        circuitKey := models.CircuitKey{
205✔
3448
                ChanID: l.ShortChanID(),
205✔
3449
                HtlcID: add.ID,
205✔
3450
        }
205✔
3451

205✔
3452
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
205✔
3453
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
205✔
3454
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
205✔
3455
        )
205✔
3456
        if err != nil {
205✔
3457
                return err
×
3458
        }
×
3459

3460
        // Create a hodlHtlc struct and decide either resolved now or later.
3461
        htlc := hodlHtlc{
205✔
3462
                add:        add,
205✔
3463
                sourceRef:  sourceRef,
205✔
3464
                obfuscator: obfuscator,
205✔
3465
        }
205✔
3466

205✔
3467
        // If the event is nil, the invoice is being held, so we save payment
205✔
3468
        // descriptor for future reference.
205✔
3469
        if event == nil {
264✔
3470
                l.hodlMap[circuitKey] = htlc
59✔
3471
                return nil
59✔
3472
        }
59✔
3473

3474
        // Process the received resolution.
3475
        return l.processHtlcResolution(event, htlc)
149✔
3476
}
3477

3478
// settleHTLC settles the HTLC on the channel.
3479
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
3480
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
200✔
3481

200✔
3482
        hash := preimage.Hash()
200✔
3483

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

200✔
3486
        err := l.channel.SettleHTLC(
200✔
3487
                preimage, htlcIndex, &sourceRef, nil, nil,
200✔
3488
        )
200✔
3489
        if err != nil {
200✔
3490
                return fmt.Errorf("unable to settle htlc: %w", err)
×
3491
        }
×
3492

3493
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
3494
        // fake one before sending it to the peer.
3495
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
203✔
3496
                l.log.Warnf(hodl.BogusSettle.Warning())
3✔
3497
                preimage = [32]byte{}
3✔
3498
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
3✔
3499
        }
3✔
3500

3501
        // HTLC was successfully settled locally send notification about it
3502
        // remote peer.
3503
        err = l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
200✔
3504
                ChanID:          l.ChanID(),
200✔
3505
                ID:              htlcIndex,
200✔
3506
                PaymentPreimage: preimage,
200✔
3507
        })
200✔
3508
        if err != nil {
200✔
3509
                l.log.Errorf("failed to send UpdateFulfillHTLC: %v", err)
×
3510
        }
×
3511

3512
        // Once we have successfully settled the htlc, notify a settle event.
3513
        l.cfg.HtlcNotifier.NotifySettleEvent(
200✔
3514
                HtlcKey{
200✔
3515
                        IncomingCircuit: models.CircuitKey{
200✔
3516
                                ChanID: l.ShortChanID(),
200✔
3517
                                HtlcID: htlcIndex,
200✔
3518
                        },
200✔
3519
                },
200✔
3520
                preimage,
200✔
3521
                HtlcEventTypeReceive,
200✔
3522
        )
200✔
3523

200✔
3524
        return nil
200✔
3525
}
3526

3527
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
3528
// err chan for the individual responses. This method is intended to be spawned
3529
// as a goroutine so the responses can be handled in the background.
3530
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
578✔
3531
        // Don't forward packets for which we already have a response in our
578✔
3532
        // mailbox. This could happen if a packet fails and is buffered in the
578✔
3533
        // mailbox, and the incoming link flaps.
578✔
3534
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
578✔
3535
        for _, pkt := range packets {
1,156✔
3536
                if l.mailBox.HasPacket(pkt.inKey()) {
581✔
3537
                        continue
3✔
3538
                }
3539

3540
                filteredPkts = append(filteredPkts, pkt)
578✔
3541
        }
3542

3543
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
578✔
3544
        if err != nil {
589✔
3545
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
3546
                        "settle/fail over htlcswitch: %v", err)
11✔
3547
        }
11✔
3548
}
3549

3550
// sendHTLCError functions cancels HTLC and send cancel message back to the
3551
// peer from which HTLC was received.
3552
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
3553
        sourceRef channeldb.AddRef, failure *LinkError,
3554
        e hop.ErrorEncrypter, isReceive bool) {
108✔
3555

108✔
3556
        reason, err := e.EncryptFirstHop(failure.WireMessage())
108✔
3557
        if err != nil {
108✔
3558
                l.log.Errorf("unable to obfuscate error: %v", err)
×
3559
                return
×
3560
        }
×
3561

3562
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
108✔
3563
        if err != nil {
108✔
3564
                l.log.Errorf("unable cancel htlc: %v", err)
×
3565
                return
×
3566
        }
×
3567

3568
        // Send the appropriate failure message depending on whether we're
3569
        // in a blinded route or not.
3570
        if err := l.sendIncomingHTLCFailureMsg(
108✔
3571
                add.ID, e, reason,
108✔
3572
        ); err != nil {
108✔
3573
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
3574
                return
×
3575
        }
×
3576

3577
        // Notify a link failure on our incoming link. Outgoing htlc information
3578
        // is not available at this point, because we have not decrypted the
3579
        // onion, so it is excluded.
3580
        var eventType HtlcEventType
108✔
3581
        if isReceive {
216✔
3582
                eventType = HtlcEventTypeReceive
108✔
3583
        } else {
111✔
3584
                eventType = HtlcEventTypeForward
3✔
3585
        }
3✔
3586

3587
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
108✔
3588
                HtlcKey{
108✔
3589
                        IncomingCircuit: models.CircuitKey{
108✔
3590
                                ChanID: l.ShortChanID(),
108✔
3591
                                HtlcID: add.ID,
108✔
3592
                        },
108✔
3593
                },
108✔
3594
                HtlcInfo{
108✔
3595
                        IncomingTimeLock: add.Expiry,
108✔
3596
                        IncomingAmt:      add.Amount,
108✔
3597
                },
108✔
3598
                eventType,
108✔
3599
                failure,
108✔
3600
                true,
108✔
3601
        )
108✔
3602
}
3603

3604
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
3605
// peer from which the HTLC was received. This function is primarily used to
3606
// handle the special requirements of route blinding, specifically:
3607
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
3608
// - Introduction nodes should return regular HTLC failure messages.
3609
//
3610
// It accepts the original opaque failure, which will be used in the case
3611
// that we're not part of a blinded route and an error encrypter that'll be
3612
// used if we are the introduction node and need to present an error as if
3613
// we're the failing party.
3614
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
3615
        e hop.ErrorEncrypter,
3616
        originalFailure lnwire.OpaqueReason) error {
124✔
3617

124✔
3618
        var msg lnwire.Message
124✔
3619
        switch {
124✔
3620
        // Our circuit's error encrypter will be nil if this was a locally
3621
        // initiated payment. We can only hit a blinded error for a locally
3622
        // initiated payment if we allow ourselves to be picked as the
3623
        // introduction node for our own payments and in that case we
3624
        // shouldn't reach this code. To prevent the HTLC getting stuck,
3625
        // we fail it back and log an error.
3626
        // code.
3627
        case e == nil:
×
3628
                msg = &lnwire.UpdateFailHTLC{
×
3629
                        ChanID: l.ChanID(),
×
3630
                        ID:     htlcIndex,
×
3631
                        Reason: originalFailure,
×
3632
                }
×
3633

×
3634
                l.log.Errorf("Unexpected blinded failure when "+
×
3635
                        "we are the sending node, incoming htlc: %v(%v)",
×
3636
                        l.ShortChanID(), htlcIndex)
×
3637

3638
        // For cleartext hops (ie, non-blinded/normal) we don't need any
3639
        // transformation on the error message and can just send the original.
3640
        case !e.Type().IsBlinded():
124✔
3641
                msg = &lnwire.UpdateFailHTLC{
124✔
3642
                        ChanID: l.ChanID(),
124✔
3643
                        ID:     htlcIndex,
124✔
3644
                        Reason: originalFailure,
124✔
3645
                }
124✔
3646

3647
        // When we're the introduction node, we need to convert the error to
3648
        // a UpdateFailHTLC.
3649
        case e.Type() == hop.EncrypterTypeIntroduction:
3✔
3650
                l.log.Debugf("Introduction blinded node switching out failure "+
3✔
3651
                        "error: %v", htlcIndex)
3✔
3652

3✔
3653
                // The specification does not require that we set the onion
3✔
3654
                // blob.
3✔
3655
                failureMsg := lnwire.NewInvalidBlinding(
3✔
3656
                        fn.None[[lnwire.OnionPacketSize]byte](),
3✔
3657
                )
3✔
3658
                reason, err := e.EncryptFirstHop(failureMsg)
3✔
3659
                if err != nil {
3✔
3660
                        return err
×
3661
                }
×
3662

3663
                msg = &lnwire.UpdateFailHTLC{
3✔
3664
                        ChanID: l.ChanID(),
3✔
3665
                        ID:     htlcIndex,
3✔
3666
                        Reason: reason,
3✔
3667
                }
3✔
3668

3669
        // If we are a relaying node, we need to switch out any error that
3670
        // we've received to a malformed HTLC error.
3671
        case e.Type() == hop.EncrypterTypeRelaying:
3✔
3672
                l.log.Debugf("Relaying blinded node switching out malformed "+
3✔
3673
                        "error: %v", htlcIndex)
3✔
3674

3✔
3675
                msg = &lnwire.UpdateFailMalformedHTLC{
3✔
3676
                        ChanID:      l.ChanID(),
3✔
3677
                        ID:          htlcIndex,
3✔
3678
                        FailureCode: lnwire.CodeInvalidBlinding,
3✔
3679
                }
3✔
3680

3681
        default:
×
3682
                return fmt.Errorf("unexpected encrypter: %d", e)
×
3683
        }
3684

3685
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
124✔
3686
                l.log.Warnf("Send update fail failed: %v", err)
×
3687
        }
×
3688

3689
        return nil
124✔
3690
}
3691

3692
// sendMalformedHTLCError helper function which sends the malformed HTLC update
3693
// to the payment sender.
3694
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
3695
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
3696
        sourceRef *channeldb.AddRef) {
6✔
3697

6✔
3698
        shaOnionBlob := sha256.Sum256(onionBlob[:])
6✔
3699
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
6✔
3700
        if err != nil {
6✔
3701
                l.log.Errorf("unable cancel htlc: %v", err)
×
3702
                return
×
3703
        }
×
3704

3705
        err = l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
6✔
3706
                ChanID:       l.ChanID(),
6✔
3707
                ID:           htlcIndex,
6✔
3708
                ShaOnionBlob: shaOnionBlob,
6✔
3709
                FailureCode:  code,
6✔
3710
        })
6✔
3711
        if err != nil {
6✔
3712
                l.log.Errorf("failed to send UpdateFailMalformedHTLC: %v", err)
×
3713
        }
×
3714
}
3715

3716
// failf is a function which is used to encapsulate the action necessary for
3717
// properly failing the link. It takes a LinkFailureError, which will be passed
3718
// to the OnChannelFailure closure, in order for it to determine if we should
3719
// force close the channel, and if we should send an error message to the
3720
// remote peer.
3721
func (l *channelLink) failf(linkErr LinkFailureError, format string,
3722
        a ...interface{}) {
18✔
3723

18✔
3724
        reason := fmt.Errorf(format, a...)
18✔
3725

18✔
3726
        // Return if we have already notified about a failure.
18✔
3727
        if l.failed {
21✔
3728
                l.log.Warnf("ignoring link failure (%v), as link already "+
3✔
3729
                        "failed", reason)
3✔
3730
                return
3✔
3731
        }
3✔
3732

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

18✔
3735
        // Set failed, such that we won't process any more updates, and notify
18✔
3736
        // the peer about the failure.
18✔
3737
        l.failed = true
18✔
3738
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
18✔
3739
}
3740

3741
// FundingCustomBlob returns the custom funding blob of the channel that this
3742
// link is associated with. The funding blob represents static information about
3743
// the channel that was created at channel funding time.
3744
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
3745
        if l.channel == nil {
×
3746
                return fn.None[tlv.Blob]()
×
3747
        }
×
3748

3749
        if l.channel.State() == nil {
×
3750
                return fn.None[tlv.Blob]()
×
3751
        }
×
3752

3753
        return l.channel.State().CustomBlob
×
3754
}
3755

3756
// CommitmentCustomBlob returns the custom blob of the current local commitment
3757
// of the channel that this link is associated with.
3758
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
3759
        if l.channel == nil {
×
3760
                return fn.None[tlv.Blob]()
×
3761
        }
×
3762

3763
        return l.channel.LocalCommitmentBlob()
×
3764
}
3765

3766
// handleHtlcResolution takes an HTLC resolution and processes it by draining
3767
// the hodlQueue. Once processed, a commit_sig is sent to the remote to update
3768
// their commitment.
3769
func (l *channelLink) handleHtlcResolution(ctx context.Context,
3770
        hodlItem any) error {
58✔
3771

58✔
3772
        htlcResolution, ok := hodlItem.(invoices.HtlcResolution)
58✔
3773
        if !ok {
58✔
3774
                return fmt.Errorf("expect HtlcResolution, got %T", hodlItem)
×
3775
        }
×
3776

3777
        err := l.processHodlQueue(ctx, htlcResolution)
58✔
3778
        // No error, success.
58✔
3779
        if err == nil {
115✔
3780
                return nil
57✔
3781
        }
57✔
3782

3783
        switch {
1✔
3784
        // If the duplicate keystone error was encountered, fail back
3785
        // gracefully.
3786
        case errors.Is(err, ErrDuplicateKeystone):
×
3787
                l.failf(
×
3788
                        LinkFailureError{
×
3789
                                code: ErrCircuitError,
×
3790
                        },
×
3791
                        "process hodl queue: temporary circuit error: %v", err,
×
3792
                )
×
3793

3794
        // Send an Error message to the peer.
3795
        default:
1✔
3796
                l.failf(
1✔
3797
                        LinkFailureError{
1✔
3798
                                code: ErrInternalError,
1✔
3799
                        },
1✔
3800
                        "process hodl queue: unable to update commitment: %v",
1✔
3801
                        err,
1✔
3802
                )
1✔
3803
        }
3804

3805
        return err
1✔
3806
}
3807

3808
// handleQuiescenceReq takes a locally initialized (RPC) quiescence request and
3809
// forwards it to the quiescer for further processing.
3810
func (l *channelLink) handleQuiescenceReq(req StfuReq) error {
4✔
3811
        l.quiescer.InitStfu(req)
4✔
3812

4✔
3813
        if !l.noDanglingUpdates(lntypes.Local) {
4✔
3814
                return nil
×
3815
        }
×
3816

3817
        err := l.quiescer.SendOwedStfu()
4✔
3818
        if err != nil {
4✔
3819
                l.stfuFailf("SendOwedStfu: %v", err)
×
3820
                res := fn.Err[lntypes.ChannelParty](err)
×
3821
                req.Resolve(res)
×
3822
        }
×
3823

3824
        return err
4✔
3825
}
3826

3827
// handleUpdateFee is called whenever the `updateFeeTimer` ticks. It is used to
3828
// decide whether we should send an `update_fee` msg to update the commitment's
3829
// feerate.
3830
func (l *channelLink) handleUpdateFee(ctx context.Context) error {
4✔
3831
        // If we're not the initiator of the channel, we don't control the fees,
4✔
3832
        // so we can ignore this.
4✔
3833
        if !l.channel.IsInitiator() {
4✔
3834
                return nil
×
3835
        }
×
3836

3837
        // If we are the initiator, then we'll sample the current fee rate to
3838
        // get into the chain within 3 blocks.
3839
        netFee, err := l.sampleNetworkFee()
4✔
3840
        if err != nil {
4✔
3841
                return fmt.Errorf("unable to sample network fee: %w", err)
×
3842
        }
×
3843

3844
        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
4✔
3845

4✔
3846
        newCommitFee := l.channel.IdealCommitFeeRate(
4✔
3847
                netFee, minRelayFee,
4✔
3848
                l.cfg.MaxAnchorsCommitFeeRate,
4✔
3849
                l.cfg.MaxFeeAllocation,
4✔
3850
        )
4✔
3851

4✔
3852
        // We determine if we should adjust the commitment fee based on the
4✔
3853
        // current commitment fee, the suggested new commitment fee and the
4✔
3854
        // current minimum relay fee rate.
4✔
3855
        commitFee := l.channel.CommitFeeRate()
4✔
3856
        if !shouldAdjustCommitFee(newCommitFee, commitFee, minRelayFee) {
5✔
3857
                return nil
1✔
3858
        }
1✔
3859

3860
        // If we do, then we'll send a new UpdateFee message to the remote
3861
        // party, to be locked in with a new update.
3862
        err = l.updateChannelFee(ctx, newCommitFee)
3✔
3863
        if err != nil {
3✔
3864
                return fmt.Errorf("unable to update fee rate: %w", err)
×
3865
        }
×
3866

3867
        return nil
3✔
3868
}
3869

3870
// toggleBatchTicker checks whether we need to resume or pause the batch ticker.
3871
// When we have no pending updates, the ticker is paused, otherwise resumed.
3872
func (l *channelLink) toggleBatchTicker() {
4,210✔
3873
        // If the previous event resulted in a non-empty batch, resume the batch
4,210✔
3874
        // ticker so that it can be cleared. Otherwise pause the ticker to
4,210✔
3875
        // prevent waking up the htlcManager while the batch is empty.
4,210✔
3876
        numUpdates := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
4,210✔
3877
        if numUpdates > 0 {
4,722✔
3878
                l.cfg.BatchTicker.Resume()
512✔
3879
                l.log.Tracef("BatchTicker resumed, NumPendingUpdates(Local, "+
512✔
3880
                        "Remote)=%d", numUpdates)
512✔
3881

512✔
3882
                return
512✔
3883
        }
512✔
3884

3885
        l.cfg.BatchTicker.Pause()
3,701✔
3886
        l.log.Trace("BatchTicker paused due to zero NumPendingUpdates" +
3,701✔
3887
                "(Local, Remote)")
3,701✔
3888
}
3889

3890
// resumeLink is called when starting a previous link. It will go through the
3891
// reestablishment protocol and reforwarding packets that are yet resolved.
3892
func (l *channelLink) resumeLink(ctx context.Context) error {
216✔
3893
        // If this isn't the first time that this channel link has been created,
216✔
3894
        // then we'll need to check to see if we need to re-synchronize state
216✔
3895
        // with the remote peer. settledHtlcs is a map of HTLC's that we
216✔
3896
        // re-settled as part of the channel state sync.
216✔
3897
        if l.cfg.SyncStates {
389✔
3898
                err := l.syncChanStates(ctx)
173✔
3899
                if err != nil {
176✔
3900
                        l.handleChanSyncErr(err)
3✔
3901

3✔
3902
                        return err
3✔
3903
                }
3✔
3904
        }
3905

3906
        // If a shutdown message has previously been sent on this link, then we
3907
        // need to make sure that we have disabled any HTLC adds on the outgoing
3908
        // direction of the link and that we re-resend the same shutdown message
3909
        // that we previously sent.
3910
        //
3911
        // TODO(yy): we should either move this to chanCloser, or move all
3912
        // shutdown handling logic to be managed by the link, but not a mixed of
3913
        // partial management by two subsystems.
3914
        l.cfg.PreviouslySentShutdown.WhenSome(func(shutdown lnwire.Shutdown) {
219✔
3915
                // Immediately disallow any new outgoing HTLCs.
3✔
3916
                if !l.DisableAdds(Outgoing) {
3✔
3917
                        l.log.Warnf("Outgoing link adds already disabled")
×
3918
                }
×
3919

3920
                // Re-send the shutdown message the peer. Since syncChanStates
3921
                // would have sent any outstanding CommitSig, it is fine for us
3922
                // to immediately queue the shutdown message now.
3923
                err := l.cfg.Peer.SendMessage(false, &shutdown)
3✔
3924
                if err != nil {
3✔
3925
                        l.log.Warnf("Error sending shutdown message: %v", err)
×
3926
                }
×
3927
        })
3928

3929
        // We've successfully reestablished the channel, mark it as such to
3930
        // allow the switch to forward HTLCs in the outbound direction.
3931
        l.markReestablished()
216✔
3932

216✔
3933
        // With the channel states synced, we now reset the mailbox to ensure we
216✔
3934
        // start processing all unacked packets in order. This is done here to
216✔
3935
        // ensure that all acknowledgments that occur during channel
216✔
3936
        // resynchronization have taken affect, causing us only to pull unacked
216✔
3937
        // packets after starting to read from the downstream mailbox.
216✔
3938
        err := l.mailBox.ResetPackets()
216✔
3939
        if err != nil {
216✔
3940
                l.log.Errorf("failed to reset packets: %v", err)
×
3941
        }
×
3942

3943
        // If the channel is pending, there's no need to reforwarding packets.
3944
        if l.ShortChanID() == hop.Source {
216✔
3945
                return nil
×
3946
        }
×
3947

3948
        // After cleaning up any memory pertaining to incoming packets, we now
3949
        // replay our forwarding packages to handle any htlcs that can be
3950
        // processed locally, or need to be forwarded out to the switch. We will
3951
        // only attempt to resolve packages if our short chan id indicates that
3952
        // the channel is not pending, otherwise we should have no htlcs to
3953
        // reforward.
3954
        err = l.resolveFwdPkgs(ctx)
216✔
3955
        switch {
216✔
3956
        // No error was encountered, success.
3957
        case err == nil:
215✔
3958
                // With our link's in-memory state fully reconstructed, spawn a
215✔
3959
                // goroutine to manage the reclamation of disk space occupied by
215✔
3960
                // completed forwarding packages.
215✔
3961
                l.cg.WgAdd(1)
215✔
3962
                go l.fwdPkgGarbager()
215✔
3963

215✔
3964
                return nil
215✔
3965

3966
        // If the duplicate keystone error was encountered, we'll fail without
3967
        // sending an Error message to the peer.
3968
        case errors.Is(err, ErrDuplicateKeystone):
×
3969
                l.failf(LinkFailureError{code: ErrCircuitError},
×
3970
                        "temporary circuit error: %v", err)
×
3971

3972
        // A non-nil error was encountered, send an Error message to
3973
        // the peer.
3974
        default:
1✔
3975
                l.failf(LinkFailureError{code: ErrInternalError},
1✔
3976
                        "unable to resolve fwd pkgs: %v", err)
1✔
3977
        }
3978

3979
        return err
1✔
3980
}
3981

3982
// processRemoteUpdateAddHTLC takes an `UpdateAddHTLC` msg sent from the remote
3983
// and processes it.
3984
func (l *channelLink) processRemoteUpdateAddHTLC(
3985
        msg *lnwire.UpdateAddHTLC) error {
453✔
3986

453✔
3987
        if l.IsFlushing(Incoming) {
453✔
3988
                // This is forbidden by the protocol specification. The best
×
3989
                // chance we have to deal with this is to drop the connection.
×
3990
                // This should roll back the channel state to the last
×
3991
                // CommitSig. If the remote has already sent a CommitSig we
×
3992
                // haven't received yet, channel state will be re-synchronized
×
3993
                // with a ChannelReestablish message upon reconnection and the
×
3994
                // protocol state that caused us to flush the link will be
×
3995
                // rolled back. In the event that there was some
×
3996
                // non-deterministic behavior in the remote that caused them to
×
3997
                // violate the protocol, we have a decent shot at correcting it
×
3998
                // this way, since reconnecting will put us in the cleanest
×
3999
                // possible state to try again.
×
4000
                //
×
4001
                // In addition to the above, it is possible for us to hit this
×
4002
                // case in situations where we improperly handle message
×
4003
                // ordering due to concurrency choices. An issue has been filed
×
4004
                // to address this here:
×
4005
                // https://github.com/lightningnetwork/lnd/issues/8393
×
4006
                err := errors.New("received add while link is flushing")
×
4007
                l.failf(
×
4008
                        LinkFailureError{
×
4009
                                code:             ErrInvalidUpdate,
×
4010
                                FailureAction:    LinkFailureDisconnect,
×
4011
                                PermanentFailure: false,
×
4012
                                Warning:          true,
×
4013
                        }, "%v", err,
×
4014
                )
×
4015

×
4016
                return err
×
4017
        }
×
4018

4019
        // Disallow htlcs with blinding points set if we haven't enabled the
4020
        // feature. This saves us from having to process the onion at all, but
4021
        // will only catch blinded payments where we are a relaying node (as the
4022
        // blinding point will be in the payload when we're the introduction
4023
        // node).
4024
        if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
453✔
4025
                err := errors.New("blinding point included when route " +
×
4026
                        "blinding is disabled")
×
4027

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

×
4030
                return err
×
4031
        }
×
4032

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

×
4041
                return err
×
4042
        }
×
4043

4044
        // We just received an add request from an upstream peer, so we add it
4045
        // to our state machine, then add the HTLC to our "settle" list in the
4046
        // event that we know the preimage.
4047
        index, err := l.channel.ReceiveHTLC(msg)
453✔
4048
        if err != nil {
453✔
4049
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
4050
                        "unable to handle upstream add HTLC: %v", err)
×
4051

×
4052
                return err
×
4053
        }
×
4054

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

453✔
4058
        return nil
453✔
4059
}
4060

4061
// processRemoteUpdateFulfillHTLC takes an `UpdateFulfillHTLC` msg sent from the
4062
// remote and processes it.
4063
func (l *channelLink) processRemoteUpdateFulfillHTLC(
4064
        msg *lnwire.UpdateFulfillHTLC) error {
230✔
4065

230✔
4066
        pre := msg.PaymentPreimage
230✔
4067
        idx := msg.ID
230✔
4068

230✔
4069
        // Before we pipeline the settle, we'll check the set of active htlc's
230✔
4070
        // to see if the related UpdateAddHTLC has been fully locked-in.
230✔
4071
        var lockedin bool
230✔
4072
        htlcs := l.channel.ActiveHtlcs()
230✔
4073
        for _, add := range htlcs {
1,058✔
4074
                // The HTLC will be outgoing and match idx.
828✔
4075
                if !add.Incoming && add.HtlcIndex == idx {
1,056✔
4076
                        lockedin = true
228✔
4077
                        break
228✔
4078
                }
4079
        }
4080

4081
        if !lockedin {
232✔
4082
                err := errors.New("unable to handle upstream settle")
2✔
4083
                l.failf(LinkFailureError{code: ErrInvalidUpdate}, "%v", err)
2✔
4084

2✔
4085
                return err
2✔
4086
        }
2✔
4087

4088
        if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
231✔
4089
                l.failf(
3✔
4090
                        LinkFailureError{
3✔
4091
                                code:          ErrInvalidUpdate,
3✔
4092
                                FailureAction: LinkFailureForceClose,
3✔
4093
                        },
3✔
4094
                        "unable to handle upstream settle HTLC: %v", err,
3✔
4095
                )
3✔
4096

3✔
4097
                return err
3✔
4098
        }
3✔
4099

4100
        settlePacket := &htlcPacket{
228✔
4101
                outgoingChanID: l.ShortChanID(),
228✔
4102
                outgoingHTLCID: idx,
228✔
4103
                htlc: &lnwire.UpdateFulfillHTLC{
228✔
4104
                        PaymentPreimage: pre,
228✔
4105
                },
228✔
4106
        }
228✔
4107

228✔
4108
        // Add the newly discovered preimage to our growing list of uncommitted
228✔
4109
        // preimage. These will be written to the witness cache just before
228✔
4110
        // accepting the next commitment signature from the remote peer.
228✔
4111
        l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
228✔
4112

228✔
4113
        // Pipeline this settle, send it to the switch.
228✔
4114
        go l.forwardBatch(false, settlePacket)
228✔
4115

228✔
4116
        return nil
228✔
4117
}
4118

4119
// processRemoteUpdateFailMalformedHTLC takes an `UpdateFailMalformedHTLC` msg
4120
// sent from the remote and processes it.
4121
func (l *channelLink) processRemoteUpdateFailMalformedHTLC(
4122
        msg *lnwire.UpdateFailMalformedHTLC) error {
6✔
4123

6✔
4124
        // Convert the failure type encoded within the HTLC fail message to the
6✔
4125
        // proper generic lnwire error code.
6✔
4126
        var failure lnwire.FailureMessage
6✔
4127
        switch msg.FailureCode {
6✔
4128
        case lnwire.CodeInvalidOnionVersion:
4✔
4129
                failure = &lnwire.FailInvalidOnionVersion{
4✔
4130
                        OnionSHA256: msg.ShaOnionBlob,
4✔
4131
                }
4✔
4132
        case lnwire.CodeInvalidOnionHmac:
×
4133
                failure = &lnwire.FailInvalidOnionHmac{
×
4134
                        OnionSHA256: msg.ShaOnionBlob,
×
4135
                }
×
4136

4137
        case lnwire.CodeInvalidOnionKey:
×
4138
                failure = &lnwire.FailInvalidOnionKey{
×
4139
                        OnionSHA256: msg.ShaOnionBlob,
×
4140
                }
×
4141

4142
        // Handle malformed errors that are part of a blinded route. This case
4143
        // is slightly different, because we expect every relaying node in the
4144
        // blinded portion of the route to send malformed errors. If we're also
4145
        // a relaying node, we're likely going to switch this error out anyway
4146
        // for our own malformed error, but we handle the case here for
4147
        // completeness.
4148
        case lnwire.CodeInvalidBlinding:
3✔
4149
                failure = &lnwire.FailInvalidBlinding{
3✔
4150
                        OnionSHA256: msg.ShaOnionBlob,
3✔
4151
                }
3✔
4152

4153
        default:
2✔
4154
                l.log.Warnf("unexpected failure code received in "+
2✔
4155
                        "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
4156

2✔
4157
                // We don't just pass back the error we received from our
2✔
4158
                // successor. Otherwise we might report a failure that penalizes
2✔
4159
                // us more than needed. If the onion that we forwarded was
2✔
4160
                // correct, the node should have been able to send back its own
2✔
4161
                // failure. The node did not send back its own failure, so we
2✔
4162
                // assume there was a problem with the onion and report that
2✔
4163
                // back. We reuse the invalid onion key failure because there is
2✔
4164
                // no specific error for this case.
2✔
4165
                failure = &lnwire.FailInvalidOnionKey{
2✔
4166
                        OnionSHA256: msg.ShaOnionBlob,
2✔
4167
                }
2✔
4168
        }
4169

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

4176
        // If remote side have been unable to parse the onion blob we have sent
4177
        // to it, than we should transform the malformed HTLC message to the
4178
        // usual HTLC fail message.
4179
        err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
6✔
4180
        if err != nil {
6✔
4181
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
4182
                        "unable to handle upstream fail HTLC: %v", err)
×
4183

×
4184
                return err
×
4185
        }
×
4186

4187
        return nil
6✔
4188
}
4189

4190
// processRemoteUpdateFailHTLC takes an `UpdateFailHTLC` msg sent from the
4191
// remote and processes it.
4192
func (l *channelLink) processRemoteUpdateFailHTLC(
4193
        msg *lnwire.UpdateFailHTLC) error {
123✔
4194

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

123✔
4198
        if len(msg.Reason) < minimumFailReasonLength {
124✔
4199
                // We've received a reason with a non-compliant length. Older
1✔
4200
                // nodes happily relay back these failures that may originate
1✔
4201
                // from a node further downstream. Therefore we can't just fail
1✔
4202
                // the channel.
1✔
4203
                //
1✔
4204
                // We want to be compliant ourselves, so we also can't pass back
1✔
4205
                // the reason unmodified. And we must make sure that we don't
1✔
4206
                // hit the magic length check of 260 bytes in
1✔
4207
                // processRemoteSettleFails either.
1✔
4208
                //
1✔
4209
                // Because the reason is unreadable for the payer anyway, we
1✔
4210
                // just replace it by a compliant-length series of random bytes.
1✔
4211
                msg.Reason = make([]byte, minimumFailReasonLength)
1✔
4212
                _, err := crand.Read(msg.Reason[:])
1✔
4213
                if err != nil {
1✔
4214
                        return fmt.Errorf("random generation error: %w", err)
×
4215
                }
×
4216
        }
4217

4218
        // Add fail to the update log.
4219
        idx := msg.ID
123✔
4220
        err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
123✔
4221
        if err != nil {
123✔
4222
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
4223
                        "unable to handle upstream fail HTLC: %v", err)
×
4224

×
4225
                return err
×
4226
        }
×
4227

4228
        return nil
123✔
4229
}
4230

4231
// processRemoteCommitSig takes a `CommitSig` msg sent from the remote and
4232
// processes it.
4233
func (l *channelLink) processRemoteCommitSig(ctx context.Context,
4234
        msg *lnwire.CommitSig) error {
1,219✔
4235

1,219✔
4236
        // Since we may have learned new preimages for the first time, we'll add
1,219✔
4237
        // them to our preimage cache. By doing this, we ensure any contested
1,219✔
4238
        // contracts watched by any on-chain arbitrators can now sweep this HTLC
1,219✔
4239
        // on-chain. We delay committing the preimages until just before
1,219✔
4240
        // accepting the new remote commitment, as afterwards the peer won't
1,219✔
4241
        // resend the Settle messages on the next channel reestablishment. Doing
1,219✔
4242
        // so allows us to more effectively batch this operation, instead of
1,219✔
4243
        // doing a single write per preimage.
1,219✔
4244
        err := l.cfg.PreimageCache.AddPreimages(l.uncommittedPreimages...)
1,219✔
4245
        if err != nil {
1,219✔
4246
                l.failf(
×
4247
                        LinkFailureError{code: ErrInternalError},
×
4248
                        "unable to add preimages=%v to cache: %v",
×
4249
                        l.uncommittedPreimages, err,
×
4250
                )
×
4251

×
4252
                return err
×
4253
        }
×
4254

4255
        // Instead of truncating the slice to conserve memory allocations, we
4256
        // simply set the uncommitted preimage slice to nil so that a new one
4257
        // will be initialized if any more witnesses are discovered. We do this
4258
        // because the maximum size that the slice can occupy is 15KB, and we
4259
        // want to ensure we release that memory back to the runtime.
4260
        l.uncommittedPreimages = nil
1,219✔
4261

1,219✔
4262
        // We just received a new updates to our local commitment chain,
1,219✔
4263
        // validate this new commitment, closing the link if invalid.
1,219✔
4264
        auxSigBlob, err := msg.CustomRecords.Serialize()
1,219✔
4265
        if err != nil {
1,219✔
4266
                l.failf(
×
4267
                        LinkFailureError{code: ErrInvalidCommitment},
×
4268
                        "unable to serialize custom records: %v", err,
×
4269
                )
×
4270

×
4271
                return err
×
4272
        }
×
4273
        err = l.channel.ReceiveNewCommitment(&lnwallet.CommitSigs{
1,219✔
4274
                CommitSig:  msg.CommitSig,
1,219✔
4275
                HtlcSigs:   msg.HtlcSigs,
1,219✔
4276
                PartialSig: msg.PartialSig,
1,219✔
4277
                AuxSigBlob: auxSigBlob,
1,219✔
4278
        })
1,219✔
4279
        if err != nil {
1,219✔
4280
                // If we were unable to reconstruct their proposed commitment,
×
4281
                // then we'll examine the type of error. If it's an
×
4282
                // InvalidCommitSigError, then we'll send a direct error.
×
4283
                var sendData []byte
×
4284
                switch {
×
4285
                case lnutils.ErrorAs[*lnwallet.InvalidCommitSigError](err):
×
4286
                        sendData = []byte(err.Error())
×
4287
                case lnutils.ErrorAs[*lnwallet.InvalidHtlcSigError](err):
×
4288
                        sendData = []byte(err.Error())
×
4289
                }
4290
                l.failf(
×
4291
                        LinkFailureError{
×
4292
                                code:          ErrInvalidCommitment,
×
4293
                                FailureAction: LinkFailureForceClose,
×
4294
                                SendData:      sendData,
×
4295
                        },
×
4296
                        "ChannelPoint(%v): unable to accept new "+
×
4297
                                "commitment: %v",
×
4298
                        l.channel.ChannelPoint(), err,
×
4299
                )
×
4300

×
4301
                return err
×
4302
        }
4303

4304
        // As we've just accepted a new state, we'll now immediately send the
4305
        // remote peer a revocation for our prior state.
4306
        nextRevocation, currentHtlcs, finalHTLCs, err :=
1,219✔
4307
                l.channel.RevokeCurrentCommitment()
1,219✔
4308
        if err != nil {
1,219✔
4309
                l.log.Errorf("unable to revoke commitment: %v", err)
×
4310

×
4311
                // We need to fail the channel in case revoking our local
×
4312
                // commitment does not succeed. We might have already advanced
×
4313
                // our channel state which would lead us to proceed with an
×
4314
                // unclean state.
×
4315
                //
×
4316
                // NOTE: We do not trigger a force close because this could
×
4317
                // resolve itself in case our db was just busy not accepting new
×
4318
                // transactions.
×
4319
                l.failf(
×
4320
                        LinkFailureError{
×
4321
                                code:          ErrInternalError,
×
4322
                                Warning:       true,
×
4323
                                FailureAction: LinkFailureDisconnect,
×
4324
                        },
×
4325
                        "ChannelPoint(%v): unable to accept new "+
×
4326
                                "commitment: %v",
×
4327
                        l.channel.ChannelPoint(), err,
×
4328
                )
×
4329

×
4330
                return err
×
4331
        }
×
4332

4333
        // As soon as we are ready to send our next revocation, we can invoke
4334
        // the incoming commit hooks.
4335
        l.Lock()
1,219✔
4336
        l.incomingCommitHooks.invoke()
1,219✔
4337
        l.Unlock()
1,219✔
4338

1,219✔
4339
        err = l.cfg.Peer.SendMessage(false, nextRevocation)
1,219✔
4340
        if err != nil {
1,220✔
4341
                l.log.Errorf("failed to send RevokeAndAck: %v", err)
1✔
4342
        }
1✔
4343

4344
        // Notify the incoming htlcs of which the resolutions were locked in.
4345
        for id, settled := range finalHTLCs {
1,553✔
4346
                l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
334✔
4347
                        models.CircuitKey{
334✔
4348
                                ChanID: l.ShortChanID(),
334✔
4349
                                HtlcID: id,
334✔
4350
                        },
334✔
4351
                        channeldb.FinalHtlcInfo{
334✔
4352
                                Settled:  settled,
334✔
4353
                                Offchain: true,
334✔
4354
                        },
334✔
4355
                )
334✔
4356
        }
334✔
4357

4358
        // Since we just revoked our commitment, we may have a new set of HTLC's
4359
        // on our commitment, so we'll send them using our function closure
4360
        // NotifyContractUpdate.
4361
        newUpdate := &contractcourt.ContractUpdate{
1,219✔
4362
                HtlcKey: contractcourt.LocalHtlcSet,
1,219✔
4363
                Htlcs:   currentHtlcs,
1,219✔
4364
        }
1,219✔
4365
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,219✔
4366
        if err != nil {
1,219✔
4367
                return fmt.Errorf("unable to notify contract update: %w", err)
×
4368
        }
×
4369

4370
        select {
1,219✔
4371
        case <-l.cg.Done():
×
4372
                return nil
×
4373
        default:
1,219✔
4374
        }
4375

4376
        // If the remote party initiated the state transition, we'll reply with
4377
        // a signature to provide them with their version of the latest
4378
        // commitment. Otherwise, both commitment chains are fully synced from
4379
        // our PoV, then we don't need to reply with a signature as both sides
4380
        // already have a commitment with the latest accepted.
4381
        if l.channel.OweCommitment() {
1,881✔
4382
                if !l.updateCommitTxOrFail(ctx) {
663✔
4383
                        return nil
1✔
4384
                }
1✔
4385
        }
4386

4387
        // If we need to send out an Stfu, this would be the time to do so.
4388
        if l.noDanglingUpdates(lntypes.Local) {
2,338✔
4389
                err = l.quiescer.SendOwedStfu()
1,120✔
4390
                if err != nil {
1,120✔
4391
                        l.stfuFailf("sendOwedStfu: %v", err)
×
4392
                }
×
4393
        }
4394

4395
        // Now that we have finished processing the incoming CommitSig and sent
4396
        // out our RevokeAndAck, we invoke the flushHooks if the channel state
4397
        // is clean.
4398
        l.Lock()
1,218✔
4399
        if l.channel.IsChannelClean() {
1,429✔
4400
                l.flushHooks.invoke()
211✔
4401
        }
211✔
4402
        l.Unlock()
1,218✔
4403

1,218✔
4404
        return nil
1,218✔
4405
}
4406

4407
// processRemoteRevokeAndAck takes a `RevokeAndAck` msg sent from the remote and
4408
// processes it.
4409
func (l *channelLink) processRemoteRevokeAndAck(ctx context.Context,
4410
        msg *lnwire.RevokeAndAck) error {
1,207✔
4411

1,207✔
4412
        // We've received a revocation from the remote chain, if valid, this
1,207✔
4413
        // moves the remote chain forward, and expands our revocation window.
1,207✔
4414

1,207✔
4415
        // We now process the message and advance our remote commit chain.
1,207✔
4416
        fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
1,207✔
4417
        if err != nil {
1,207✔
4418
                // TODO(halseth): force close?
×
4419
                l.failf(
×
4420
                        LinkFailureError{
×
4421
                                code:          ErrInvalidRevocation,
×
4422
                                FailureAction: LinkFailureDisconnect,
×
4423
                        },
×
4424
                        "unable to accept revocation: %v", err,
×
4425
                )
×
4426

×
4427
                return err
×
4428
        }
×
4429

4430
        // The remote party now has a new primary commitment, so we'll update
4431
        // the contract court to be aware of this new set (the prior old remote
4432
        // pending).
4433
        newUpdate := &contractcourt.ContractUpdate{
1,207✔
4434
                HtlcKey: contractcourt.RemoteHtlcSet,
1,207✔
4435
                Htlcs:   remoteHTLCs,
1,207✔
4436
        }
1,207✔
4437
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,207✔
4438
        if err != nil {
1,207✔
4439
                return fmt.Errorf("unable to notify contract update: %w", err)
×
4440
        }
×
4441

4442
        select {
1,207✔
4443
        case <-l.cg.Done():
2✔
4444
                return nil
2✔
4445
        default:
1,205✔
4446
        }
4447

4448
        // If we have a tower client for this channel type, we'll create a
4449
        // backup for the current state.
4450
        if l.cfg.TowerClient != nil {
1,208✔
4451
                state := l.channel.State()
3✔
4452
                chanID := l.ChanID()
3✔
4453

3✔
4454
                err = l.cfg.TowerClient.BackupState(
3✔
4455
                        &chanID, state.RemoteCommitment.CommitHeight-1,
3✔
4456
                )
3✔
4457
                if err != nil {
3✔
4458
                        l.failf(LinkFailureError{
×
4459
                                code: ErrInternalError,
×
4460
                        }, "unable to queue breach backup: %v", err)
×
4461

×
4462
                        return err
×
4463
                }
×
4464
        }
4465

4466
        // If we can send updates then we can process adds in case we are the
4467
        // exit hop and need to send back resolutions, or in case there are
4468
        // validity issues with the packets. Otherwise we defer the action until
4469
        // resume.
4470
        //
4471
        // We are free to process the settles and fails without this check since
4472
        // processing those can't result in further updates to this channel
4473
        // link.
4474
        if l.quiescer.CanSendUpdates() {
2,409✔
4475
                l.processRemoteAdds(fwdPkg)
1,204✔
4476
        } else {
1,205✔
4477
                l.quiescer.OnResume(func() {
1✔
4478
                        l.processRemoteAdds(fwdPkg)
×
4479
                })
×
4480
        }
4481
        l.processRemoteSettleFails(fwdPkg)
1,205✔
4482

1,205✔
4483
        // If the link failed during processing the adds, we must return to
1,205✔
4484
        // ensure we won't attempted to update the state further.
1,205✔
4485
        if l.failed {
1,205✔
4486
                return nil
×
4487
        }
×
4488

4489
        // The revocation window opened up. If there are pending local updates,
4490
        // try to update the commit tx. Pending updates could already have been
4491
        // present because of a previously failed update to the commit tx or
4492
        // freshly added in by processRemoteAdds. Also in case there are no
4493
        // local updates, but there are still remote updates that are not in the
4494
        // remote commit tx yet, send out an update.
4495
        if l.channel.OweCommitment() {
1,542✔
4496
                if !l.updateCommitTxOrFail(ctx) {
343✔
4497
                        return nil
6✔
4498
                }
6✔
4499
        }
4500

4501
        // Now that we have finished processing the RevokeAndAck, we can invoke
4502
        // the flushHooks if the channel state is clean.
4503
        l.Lock()
1,199✔
4504
        if l.channel.IsChannelClean() {
1,361✔
4505
                l.flushHooks.invoke()
162✔
4506
        }
162✔
4507
        l.Unlock()
1,199✔
4508

1,199✔
4509
        return nil
1,199✔
4510
}
4511

4512
// processRemoteUpdateFee takes an `UpdateFee` msg sent from the remote and
4513
// processes it.
4514
func (l *channelLink) processRemoteUpdateFee(msg *lnwire.UpdateFee) error {
3✔
4515
        // Check and see if their proposed fee-rate would make us exceed the fee
3✔
4516
        // threshold.
3✔
4517
        fee := chainfee.SatPerKWeight(msg.FeePerKw)
3✔
4518

3✔
4519
        isDust, err := l.exceedsFeeExposureLimit(fee)
3✔
4520
        if err != nil {
3✔
4521
                // This shouldn't typically happen. If it does, it indicates
×
4522
                // something is wrong with our channel state.
×
4523
                l.log.Errorf("Unable to determine if fee threshold " +
×
4524
                        "exceeded")
×
4525
                l.failf(LinkFailureError{code: ErrInternalError},
×
4526
                        "error calculating fee exposure: %v", err)
×
4527

×
4528
                return err
×
4529
        }
×
4530

4531
        if isDust {
3✔
4532
                // The proposed fee-rate makes us exceed the fee threshold.
×
4533
                l.failf(LinkFailureError{code: ErrInternalError},
×
4534
                        "fee threshold exceeded: %v", err)
×
4535
                return err
×
4536
        }
×
4537

4538
        // We received fee update from peer. If we are the initiator we will
4539
        // fail the channel, if not we will apply the update.
4540
        if err := l.channel.ReceiveUpdateFee(fee); err != nil {
3✔
4541
                l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
4542
                        "error receiving fee update: %v", err)
×
4543
                return err
×
4544
        }
×
4545

4546
        // Update the mailbox's feerate as well.
4547
        l.mailBox.SetFeeRate(fee)
3✔
4548

3✔
4549
        return nil
3✔
4550
}
4551

4552
// processRemoteError takes an `Error` msg sent from the remote and fails the
4553
// channel link.
4554
func (l *channelLink) processRemoteError(msg *lnwire.Error) {
2✔
4555
        // Error received from remote, MUST fail channel, but should only print
2✔
4556
        // the contents of the error message if all characters are printable
2✔
4557
        // ASCII.
2✔
4558
        l.failf(
2✔
4559
                // TODO(halseth): we currently don't fail the channel
2✔
4560
                // permanently, as there are some sync issues with other
2✔
4561
                // implementations that will lead to them sending an
2✔
4562
                // error message, but we can recover from on next
2✔
4563
                // connection. See
2✔
4564
                // https://github.com/ElementsProject/lightning/issues/4212
2✔
4565
                LinkFailureError{
2✔
4566
                        code:             ErrRemoteError,
2✔
4567
                        PermanentFailure: false,
2✔
4568
                },
2✔
4569
                "ChannelPoint(%v): received error from peer: %v",
2✔
4570
                l.channel.ChannelPoint(), msg.Error(),
2✔
4571
        )
2✔
4572
}
2✔
4573

4574
// processLocalUpdateFulfillHTLC takes an `UpdateFulfillHTLC` from the local and
4575
// processes it.
4576
func (l *channelLink) processLocalUpdateFulfillHTLC(ctx context.Context,
4577
        pkt *htlcPacket, htlc *lnwire.UpdateFulfillHTLC) {
26✔
4578

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

×
4586
                return
×
4587
        }
×
4588

4589
        // An HTLC we forward to the switch has just settled somewhere upstream.
4590
        // Therefore we settle the HTLC within the our local state machine.
4591
        inKey := pkt.inKey()
26✔
4592
        err := l.channel.SettleHTLC(
26✔
4593
                htlc.PaymentPreimage, pkt.incomingHTLCID, pkt.sourceRef,
26✔
4594
                pkt.destRef, &inKey,
26✔
4595
        )
26✔
4596
        if err != nil {
26✔
4597
                l.log.Errorf("unable to settle incoming HTLC for "+
×
4598
                        "circuit-key=%v: %v", inKey, err)
×
4599

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

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

×
4612
                return
×
4613
        }
4614

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

26✔
4618
        l.closedCircuits = append(l.closedCircuits, pkt.inKey())
26✔
4619

26✔
4620
        // With the HTLC settled, we'll need to populate the wire message to
26✔
4621
        // target the specific channel and HTLC to be canceled.
26✔
4622
        htlc.ChanID = l.ChanID()
26✔
4623
        htlc.ID = pkt.incomingHTLCID
26✔
4624

26✔
4625
        // Then we send the HTLC settle message to the connected peer so we can
26✔
4626
        // continue the propagation of the settle message.
26✔
4627
        err = l.cfg.Peer.SendMessage(false, htlc)
26✔
4628
        if err != nil {
26✔
4629
                l.log.Errorf("failed to send UpdateFulfillHTLC: %v", err)
×
4630
        }
×
4631

4632
        // Send a settle event notification to htlcNotifier.
4633
        l.cfg.HtlcNotifier.NotifySettleEvent(
26✔
4634
                newHtlcKey(pkt), htlc.PaymentPreimage, getEventType(pkt),
26✔
4635
        )
26✔
4636

26✔
4637
        // Immediately update the commitment tx to minimize latency.
26✔
4638
        l.updateCommitTxOrFail(ctx)
26✔
4639
}
4640

4641
// processLocalUpdateFailHTLC takes an `UpdateFailHTLC` from the local and
4642
// processes it.
4643
func (l *channelLink) processLocalUpdateFailHTLC(ctx context.Context,
4644
        pkt *htlcPacket, htlc *lnwire.UpdateFailHTLC) {
21✔
4645

21✔
4646
        // If hodl.FailOutgoing mode is active, we exit early to simulate
21✔
4647
        // arbitrary delays between the switch adding a FAIL to the mailbox, and
21✔
4648
        // the HTLC being added to the commitment state.
21✔
4649
        if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
21✔
4650
                l.log.Warnf(hodl.FailOutgoing.Warning())
×
4651
                l.mailBox.AckPacket(pkt.inKey())
×
4652

×
4653
                return
×
4654
        }
×
4655

4656
        // An HTLC cancellation has been triggered somewhere upstream, we'll
4657
        // remove then HTLC from our local state machine.
4658
        inKey := pkt.inKey()
21✔
4659
        err := l.channel.FailHTLC(
21✔
4660
                pkt.incomingHTLCID, htlc.Reason, pkt.sourceRef, pkt.destRef,
21✔
4661
                &inKey,
21✔
4662
        )
21✔
4663
        if err != nil {
26✔
4664
                l.log.Errorf("unable to cancel incoming HTLC for "+
5✔
4665
                        "circuit-key=%v: %v", inKey, err)
5✔
4666

5✔
4667
                // If the HTLC index for Fail response was not known to our
5✔
4668
                // commitment state, it has already been cleaned up by a prior
5✔
4669
                // response. We'll thus try to clean up any lingering state to
5✔
4670
                // ensure we don't continue reforwarding.
5✔
4671
                if lnutils.ErrorAs[lnwallet.ErrUnknownHtlcIndex](err) {
7✔
4672
                        l.cleanupSpuriousResponse(pkt)
2✔
4673
                }
2✔
4674

4675
                // Remove the packet from the link's mailbox to ensure it
4676
                // doesn't get replayed after a reconnection.
4677
                l.mailBox.AckPacket(inKey)
5✔
4678

5✔
4679
                return
5✔
4680
        }
4681

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

19✔
4685
        l.closedCircuits = append(l.closedCircuits, pkt.inKey())
19✔
4686

19✔
4687
        // With the HTLC removed, we'll need to populate the wire message to
19✔
4688
        // target the specific channel and HTLC to be canceled. The "Reason"
19✔
4689
        // field will have already been set within the switch.
19✔
4690
        htlc.ChanID = l.ChanID()
19✔
4691
        htlc.ID = pkt.incomingHTLCID
19✔
4692

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

×
4701
                return
×
4702
        }
×
4703

4704
        // If the packet does not have a link failure set, it failed further
4705
        // down the route so we notify a forwarding failure. Otherwise, we
4706
        // notify a link failure because it failed at our node.
4707
        if pkt.linkFailure != nil {
32✔
4708
                l.cfg.HtlcNotifier.NotifyLinkFailEvent(
13✔
4709
                        newHtlcKey(pkt), newHtlcInfo(pkt), getEventType(pkt),
13✔
4710
                        pkt.linkFailure, false,
13✔
4711
                )
13✔
4712
        } else {
22✔
4713
                l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
9✔
4714
                        newHtlcKey(pkt), getEventType(pkt),
9✔
4715
                )
9✔
4716
        }
9✔
4717

4718
        // Immediately update the commitment tx to minimize latency.
4719
        l.updateCommitTxOrFail(ctx)
19✔
4720
}
4721

4722
// validateHtlcAmount checks if the HTLC amount is within the policy's
4723
// minimum and maximum limits. Returns a LinkError if validation fails.
4724
func (l *channelLink) validateHtlcAmount(policy models.ForwardingPolicy,
4725
        payHash [32]byte, amt lnwire.MilliSatoshi,
4726
        originalScid lnwire.ShortChannelID,
4727
        customRecords lnwire.CustomRecords) *LinkError {
452✔
4728

452✔
4729
        // In case we are dealing with a custom HTLC, we don't need to validate
452✔
4730
        // the HTLC constraints.
452✔
4731
        //
452✔
4732
        // NOTE: Custom HTLCs are only locally sourced and will use custom
452✔
4733
        // channels which are not routable channels and should have their policy
452✔
4734
        // not restricted in the first place. However to be sure we skip this
452✔
4735
        // check otherwise we might end up in a loop of sending to the same
452✔
4736
        // route again and again because link errors are not persisted in
452✔
4737
        // mission control.
452✔
4738
        if fn.MapOptionZ(
452✔
4739
                l.cfg.AuxTrafficShaper,
452✔
4740
                func(ts AuxTrafficShaper) bool {
452✔
4741
                        return ts.IsCustomHTLC(customRecords)
×
4742
                },
×
4743
        ) {
×
4744

×
4745
                l.log.Debugf("Skipping htlc amount policy validation for " +
×
4746
                        "custom htlc")
×
4747

×
4748
                return nil
×
4749
        }
×
4750

4751
        // As our first sanity check, we'll ensure that the passed HTLC isn't
4752
        // too small for the next hop. If so, then we'll cancel the HTLC
4753
        // directly.
4754
        if amt < policy.MinHTLCOut {
463✔
4755
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
11✔
4756
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
11✔
4757
                        amt)
11✔
4758

11✔
4759
                // As part of the returned error, we'll send our latest routing
11✔
4760
                // policy so the sending node obtains the most up to date data.
11✔
4761
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
22✔
4762
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
11✔
4763
                }
11✔
4764
                failure := l.createFailureWithUpdate(false, originalScid, cb)
11✔
4765

11✔
4766
                return NewLinkError(failure)
11✔
4767
        }
4768

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

6✔
4775
                // As part of the returned error, we'll send our latest routing
6✔
4776
                // policy so the sending node obtains the most up-to-date data.
6✔
4777
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
12✔
4778
                        return lnwire.NewTemporaryChannelFailure(upd)
6✔
4779
                }
6✔
4780
                failure := l.createFailureWithUpdate(false, originalScid, cb)
6✔
4781

6✔
4782
                return NewDetailedLinkError(
6✔
4783
                        failure, OutgoingFailureHTLCExceedsMax,
6✔
4784
                )
6✔
4785
        }
4786

4787
        return nil
441✔
4788
}
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