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

lightningnetwork / lnd / 12058234999

27 Nov 2024 09:06PM UTC coverage: 57.847% (-1.1%) from 58.921%
12058234999

Pull #9148

github

ProofOfKeags
lnwire: convert DynPropose and DynCommit to use typed tlv records
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

142 of 177 new or added lines in 4 files covered. (80.23%)

19365 existing lines in 251 files now uncovered.

100876 of 174383 relevant lines covered (57.85%)

25338.28 hits per line

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

68.89
/htlcswitch/link.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

106
        // DecodeHopIterators facilitates batched decoding of HTLC Sphinx onion
107
        // blobs, which are then used to inform how to forward an HTLC.
108
        //
109
        // NOTE: This function assumes the same set of readers and preimages
110
        // are always presented for the same identifier.
111
        DecodeHopIterators func([]byte, []hop.DecodeHopIteratorRequest) (
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

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

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

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

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

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

332
        // channel is a lightning network channel to which we apply htlc
333
        // updates.
334
        channel *lnwallet.LightningChannel
335

336
        // cfg is a structure which carries all dependable fields/handlers
337
        // which may affect behaviour of the service.
338
        cfg ChannelLinkConfig
339

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

346
        // upstream is a channel that new messages sent from the remote peer to
347
        // the local peer will be sent across.
348
        upstream chan lnwire.Message
349

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

355
        // updateFeeTimer is the timer responsible for updating the link's
356
        // commitment fee every time it fires.
357
        updateFeeTimer *time.Timer
358

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

365
        sync.RWMutex
366

367
        // hodlQueue is used to receive exit hop htlc resolutions from invoice
368
        // registry.
369
        hodlQueue *queue.ConcurrentQueue
370

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

375
        // log is a link-specific logging instance.
376
        log btclog.Logger
377

378
        // isOutgoingAddBlocked tracks whether the channelLink can send an
379
        // UpdateAddHTLC.
380
        isOutgoingAddBlocked atomic.Bool
381

382
        // isIncomingAddBlocked tracks whether the channelLink can receive an
383
        // UpdateAddHTLC.
384
        isIncomingAddBlocked atomic.Bool
385

386
        // flushHooks is a hookMap that is triggered when we reach a channel
387
        // state with no live HTLCs.
388
        flushHooks hookMap
389

390
        // outgoingCommitHooks is a hookMap that is triggered after we send our
391
        // next CommitSig.
392
        outgoingCommitHooks hookMap
393

394
        // incomingCommitHooks is a hookMap that is triggered after we receive
395
        // our next CommitSig.
396
        incomingCommitHooks hookMap
397

398
        // quiescer is the state machine that tracks where this channel is with
399
        // respect to the quiescence protocol.
400
        quiescer Quiescer
401

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

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

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

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

425
        // newTransients is a channel that we use to accept new hooks into the
426
        // hookMap.
427
        newTransients chan func()
428
}
429

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

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

2✔
450
        return hookID
2✔
451
}
452

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

460
        m.transient = make(map[uint64]func())
2,706✔
461
}
462

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

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

215✔
475
        logPrefix := fmt.Sprintf("ChannelLink(%v):", channel.ChannelPoint())
215✔
476

215✔
477
        // If the max fee exposure isn't set, use the default.
215✔
478
        if cfg.MaxFeeExposure == 0 {
430✔
479
                cfg.MaxFeeExposure = DefaultMaxFeeExposure
215✔
480
        }
215✔
481

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

501
        quiescenceReqs := make(
215✔
502
                chan fn.Req[fn.Unit, fn.Result[lntypes.ChannelParty]], 1,
215✔
503
        )
215✔
504

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

520
// A compile time check to ensure channelLink implements the ChannelLink
521
// interface.
522
var _ ChannelLink = (*channelLink)(nil)
523

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

535
        l.log.Info("starting")
213✔
536

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

548
        l.mailBox.ResetMessages()
213✔
549
        l.hodlQueue.Start()
213✔
550

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

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

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

213✔
586
                        err := l.cfg.UpdateContractSignals(signals)
213✔
587
                        if err != nil {
213✔
588
                                l.log.Errorf("unable to update signals")
×
589
                        }
×
590
                }()
591
        }
592

593
        l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
213✔
594

213✔
595
        l.Wg.Add(1)
213✔
596
        go l.htlcManager()
213✔
597

213✔
598
        return nil
213✔
599
}
600

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

611
        l.log.Info("stopping")
202✔
612

202✔
613
        // As the link is stopping, we are no longer interested in htlc
202✔
614
        // resolutions coming from the invoice registry.
202✔
615
        l.cfg.Registry.HodlUnsubscribeAll(l.hodlQueue.ChanIn())
202✔
616

202✔
617
        if l.cfg.ChainEvents.Cancel != nil {
202✔
UNCOV
618
                l.cfg.ChainEvents.Cancel()
×
UNCOV
619
        }
×
620

621
        // Ensure the channel for the timer is drained.
622
        if l.updateFeeTimer != nil {
404✔
623
                if !l.updateFeeTimer.Stop() {
202✔
624
                        select {
×
625
                        case <-l.updateFeeTimer.C:
×
626
                        default:
×
627
                        }
628
                }
629
        }
630

631
        if l.hodlQueue != nil {
404✔
632
                l.hodlQueue.Stop()
202✔
633
        }
202✔
634

635
        close(l.Quit)
202✔
636
        l.Wg.Wait()
202✔
637

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

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

658
// WaitForShutdown blocks until the link finishes shutting down, which includes
659
// termination of all dependent goroutines.
660
func (l *channelLink) WaitForShutdown() {
×
661
        l.Wg.Wait()
×
662
}
×
663

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

613✔
674
        return l.eligibleToForward()
613✔
675
}
613✔
676

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

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

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

709
        return l.isIncomingAddBlocked.Swap(false)
6✔
710
}
711

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

720
        return !l.isIncomingAddBlocked.Swap(true)
8✔
721
}
722

723
// IsFlushing returns true when UpdateAddHtlc's are disabled in the direction of
724
// the argument.
725
func (l *channelLink) IsFlushing(linkDirection LinkDirection) bool {
1,591✔
726
        if linkDirection == Outgoing {
2,708✔
727
                return l.isOutgoingAddBlocked.Load()
1,117✔
728
        }
1,117✔
729

730
        return l.isIncomingAddBlocked.Load()
474✔
731
}
732

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

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

1✔
750
        if direction == Outgoing {
2✔
751
                queue = l.outgoingCommitHooks.newTransients
1✔
752
        } else {
1✔
753
                queue = l.incomingCommitHooks.newTransients
×
754
        }
×
755

756
        select {
1✔
757
        case queue <- hook:
1✔
758
        case <-l.Quit:
×
759
        }
760
}
761

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

1✔
774
        select {
1✔
775
        case l.quiescenceReqs <- req:
1✔
776
        case <-l.Quit:
×
777
                req.Resolve(fn.Err[lntypes.ChannelParty](ErrLinkShuttingDown))
×
778
        }
779

780
        return out
1✔
781
}
782

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

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

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

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

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

4✔
817
        return feePerKw, nil
4✔
818
}
819

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

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

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

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

844
        // Otherwise, we won't modify our fee.
845
        default:
7✔
846
                return false
7✔
847
        }
848
}
849

850
// failCb is used to cut down on the argument verbosity.
851
type failCb func(update *lnwire.ChannelUpdate1) lnwire.FailureMessage
852

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

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

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

879
        return cb(update)
22✔
880
}
881

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

170✔
889
        l.log.Infof("Attempting to re-synchronize channel: %v", chanState)
170✔
890

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

904
        var msgsToReSend []lnwire.Message
170✔
905

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

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

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

164✔
929
                        l.log.Infof("resending ChannelReady message to peer")
164✔
930

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

937
                        channelReadyMsg := lnwire.NewChannelReady(
164✔
938
                                l.ChanID(), nextRevocation,
164✔
939
                        )
164✔
940

164✔
941
                        // If this is a taproot channel, then we'll send the
164✔
942
                        // very same nonce that we sent above, as they should
164✔
943
                        // take the latest verification nonce we send.
164✔
944
                        if chanState.ChanType.IsTaproot() {
164✔
UNCOV
945
                                //nolint:lll
×
UNCOV
946
                                channelReadyMsg.NextLocalNonce = localChanSyncMsg.LocalNonce
×
UNCOV
947
                        }
×
948

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

964
                                // getAliases returns a copy of the alias slice
965
                                // so it is ok to use a pointer to the first
966
                                // entry.
UNCOV
967
                                channelReadyMsg.AliasScid = &aliases[0]
×
968
                        }
969

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

977
                // In any case, we'll then process their ChanSync message.
978
                l.log.Info("received re-establishment message from remote side")
170✔
979

170✔
980
                var (
170✔
981
                        openedCircuits []CircuitKey
170✔
982
                        closedCircuits []CircuitKey
170✔
983
                )
170✔
984

170✔
985
                // We've just received a ChanSync message from the remote
170✔
986
                // party, so we'll process the message  in order to determine
170✔
987
                // if we need to re-transmit any messages to the remote party.
170✔
988
                ctx, cancel := l.WithCtxQuitNoTimeout()
170✔
989
                defer cancel()
170✔
990
                msgsToReSend, openedCircuits, closedCircuits, err =
170✔
991
                        l.channel.ProcessChanSyncMsg(ctx, remoteChanSyncMsg)
170✔
992
                if err != nil {
170✔
UNCOV
993
                        return err
×
UNCOV
994
                }
×
995

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

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

1008
                if len(msgsToReSend) > 0 {
175✔
1009
                        l.log.Infof("sending %v updates to synchronize the "+
5✔
1010
                                "state", len(msgsToReSend))
5✔
1011
                }
5✔
1012

1013
                // If we have any messages to retransmit, we'll do so
1014
                // immediately so we return to a synchronized state as soon as
1015
                // possible.
1016
                for _, msg := range msgsToReSend {
181✔
1017
                        l.cfg.Peer.SendMessage(false, msg)
11✔
1018
                }
11✔
1019

UNCOV
1020
        case <-l.Quit:
×
UNCOV
1021
                return ErrLinkShuttingDown
×
1022
        }
1023

1024
        return nil
170✔
1025
}
1026

1027
// resolveFwdPkgs loads any forwarding packages for this link from disk, and
1028
// reprocesses them in order. The primary goal is to make sure that any HTLCs
1029
// we previously received are reinstated in memory, and forwarded to the switch
1030
// if necessary. After a restart, this will also delete any previously
1031
// completed packages.
1032
func (l *channelLink) resolveFwdPkgs() error {
213✔
1033
        fwdPkgs, err := l.channel.LoadFwdPkgs()
213✔
1034
        if err != nil {
213✔
1035
                return err
×
1036
        }
×
1037

1038
        l.log.Debugf("loaded %d fwd pks", len(fwdPkgs))
213✔
1039

213✔
1040
        for _, fwdPkg := range fwdPkgs {
219✔
1041
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
6✔
1042
                        return err
×
1043
                }
×
1044
        }
1045

1046
        // If any of our reprocessing steps require an update to the commitment
1047
        // txn, we initiate a state transition to capture all relevant changes.
1048
        if l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote) > 0 {
213✔
UNCOV
1049
                return l.updateCommitTx()
×
UNCOV
1050
        }
×
1051

1052
        return nil
213✔
1053
}
1054

1055
// resolveFwdPkg interprets the FwdState of the provided package, either
1056
// reprocesses any outstanding htlcs in the package, or performs garbage
1057
// collection on the package.
1058
func (l *channelLink) resolveFwdPkg(fwdPkg *channeldb.FwdPkg) error {
6✔
1059
        // Remove any completed packages to clear up space.
6✔
1060
        if fwdPkg.State == channeldb.FwdStateCompleted {
7✔
1061
                l.log.Debugf("removing completed fwd pkg for height=%d",
1✔
1062
                        fwdPkg.Height)
1✔
1063

1✔
1064
                err := l.channel.RemoveFwdPkgs(fwdPkg.Height)
1✔
1065
                if err != nil {
1✔
1066
                        l.log.Errorf("unable to remove fwd pkg for height=%d: "+
×
1067
                                "%v", fwdPkg.Height, err)
×
1068
                        return err
×
1069
                }
×
1070
        }
1071

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

1078
        // If the package is fully acked but not completed, it must still have
1079
        // settles and fails to propagate.
1080
        if !fwdPkg.SettleFailFilter.IsFull() {
6✔
UNCOV
1081
                l.processRemoteSettleFails(fwdPkg)
×
UNCOV
1082
        }
×
1083

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

3✔
1091
                // If the link failed during processing the adds, we must
3✔
1092
                // return to ensure we won't attempted to update the state
3✔
1093
                // further.
3✔
1094
                if l.failed {
3✔
1095
                        return fmt.Errorf("link failed while " +
×
1096
                                "processing remote adds")
×
1097
                }
×
1098
        }
1099

1100
        return nil
6✔
1101
}
1102

1103
// fwdPkgGarbager periodically reads all forwarding packages from disk and
1104
// removes those that can be discarded. It is safe to do this entirely in the
1105
// background, since all state is coordinated on disk. This also ensures the
1106
// link can continue to process messages and interleave database accesses.
1107
//
1108
// NOTE: This MUST be run as a goroutine.
1109
func (l *channelLink) fwdPkgGarbager() {
213✔
1110
        defer l.Wg.Done()
213✔
1111

213✔
1112
        l.cfg.FwdPkgGCTicker.Resume()
213✔
1113
        defer l.cfg.FwdPkgGCTicker.Stop()
213✔
1114

213✔
1115
        if err := l.loadAndRemove(); err != nil {
213✔
1116
                l.log.Warnf("unable to run initial fwd pkgs gc: %v", err)
×
1117
        }
×
1118

1119
        for {
444✔
1120
                select {
231✔
1121
                case <-l.cfg.FwdPkgGCTicker.Ticks():
18✔
1122
                        if err := l.loadAndRemove(); err != nil {
36✔
1123
                                l.log.Warnf("unable to remove fwd pkgs: %v",
18✔
1124
                                        err)
18✔
1125
                                continue
18✔
1126
                        }
1127
                case <-l.Quit:
202✔
1128
                        return
202✔
1129
                }
1130
        }
1131
}
1132

1133
// loadAndRemove loads all the channels forwarding packages and determines if
1134
// they can be removed. It is called once before the FwdPkgGCTicker ticks so that
1135
// a longer tick interval can be used.
1136
func (l *channelLink) loadAndRemove() error {
231✔
1137
        fwdPkgs, err := l.channel.LoadFwdPkgs()
231✔
1138
        if err != nil {
249✔
1139
                return err
18✔
1140
        }
18✔
1141

1142
        var removeHeights []uint64
213✔
1143
        for _, fwdPkg := range fwdPkgs {
218✔
1144
                if fwdPkg.State != channeldb.FwdStateCompleted {
10✔
1145
                        continue
5✔
1146
                }
1147

UNCOV
1148
                removeHeights = append(removeHeights, fwdPkg.Height)
×
1149
        }
1150

1151
        // If removeHeights is empty, return early so we don't use a db
1152
        // transaction.
1153
        if len(removeHeights) == 0 {
426✔
1154
                return nil
213✔
1155
        }
213✔
1156

UNCOV
1157
        return l.channel.RemoveFwdPkgs(removeHeights...)
×
1158
}
1159

1160
// handleChanSyncErr performs the error handling logic in the case where we
1161
// could not successfully syncChanStates with our channel peer.
UNCOV
1162
func (l *channelLink) handleChanSyncErr(err error) {
×
UNCOV
1163
        l.log.Warnf("error when syncing channel states: %v", err)
×
UNCOV
1164

×
UNCOV
1165
        var errDataLoss *lnwallet.ErrCommitSyncLocalDataLoss
×
UNCOV
1166

×
UNCOV
1167
        switch {
×
UNCOV
1168
        case errors.Is(err, ErrLinkShuttingDown):
×
UNCOV
1169
                l.log.Debugf("unable to sync channel states, link is " +
×
UNCOV
1170
                        "shutting down")
×
UNCOV
1171
                return
×
1172

1173
        // We failed syncing the commit chains, probably because the remote has
1174
        // lost state. We should force close the channel.
UNCOV
1175
        case errors.Is(err, lnwallet.ErrCommitSyncRemoteDataLoss):
×
UNCOV
1176
                fallthrough
×
1177

1178
        // The remote sent us an invalid last commit secret, we should force
1179
        // close the channel.
1180
        // TODO(halseth): and permanently ban the peer?
UNCOV
1181
        case errors.Is(err, lnwallet.ErrInvalidLastCommitSecret):
×
UNCOV
1182
                fallthrough
×
1183

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

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

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

1224
        // Other, unspecified error.
1225
        default:
×
1226
        }
1227

UNCOV
1228
        l.failf(
×
UNCOV
1229
                LinkFailureError{
×
UNCOV
1230
                        code:          ErrRecoveryError,
×
UNCOV
1231
                        FailureAction: LinkFailureForceNone,
×
UNCOV
1232
                },
×
UNCOV
1233
                "unable to synchronize channel states: %v", err,
×
UNCOV
1234
        )
×
1235
}
1236

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

1254
        l.log.Infof("HTLC manager started, bandwidth=%v", l.Bandwidth())
213✔
1255

213✔
1256
        // Notify any clients that the link is now in the switch via an
213✔
1257
        // ActiveLinkEvent. We'll also defer an inactive link notification for
213✔
1258
        // when the link exits to ensure that every active notification is
213✔
1259
        // matched by an inactive one.
213✔
1260
        l.cfg.NotifyActiveLink(l.ChannelPoint())
213✔
1261
        defer l.cfg.NotifyInactiveLinkEvent(l.ChannelPoint())
213✔
1262

213✔
1263
        // TODO(roasbeef): need to call wipe chan whenever D/C?
213✔
1264

213✔
1265
        // If this isn't the first time that this channel link has been
213✔
1266
        // created, then we'll need to check to see if we need to
213✔
1267
        // re-synchronize state with the remote peer. settledHtlcs is a map of
213✔
1268
        // HTLC's that we re-settled as part of the channel state sync.
213✔
1269
        if l.cfg.SyncStates {
383✔
1270
                err := l.syncChanStates()
170✔
1271
                if err != nil {
170✔
UNCOV
1272
                        l.handleChanSyncErr(err)
×
UNCOV
1273
                        return
×
UNCOV
1274
                }
×
1275
        }
1276

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

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

1296
        // We've successfully reestablished the channel, mark it as such to
1297
        // allow the switch to forward HTLCs in the outbound direction.
1298
        l.markReestablished()
213✔
1299

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

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

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

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

1333
                // A non-nil error was encountered, send an Error message to
1334
                // the peer.
1335
                default:
×
1336
                        l.failf(LinkFailureError{code: ErrInternalError},
×
1337
                                "unable to resolve fwd pkgs: %v", err)
×
1338
                        return
×
1339
                }
1340

1341
                // With our link's in-memory state fully reconstructed, spawn a
1342
                // goroutine to manage the reclamation of disk space occupied by
1343
                // completed forwarding packages.
1344
                l.Wg.Add(1)
213✔
1345
                go l.fwdPkgGarbager()
213✔
1346
        }
1347

1348
        for {
4,376✔
1349
                // We must always check if we failed at some point processing
4,163✔
1350
                // the last update before processing the next.
4,163✔
1351
                if l.failed {
4,176✔
1352
                        l.log.Errorf("link failed, exiting htlcManager")
13✔
1353
                        return
13✔
1354
                }
13✔
1355

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

1375
                select {
4,150✔
1376
                // We have a new hook that needs to be run when we reach a clean
1377
                // channel state.
1378
                case hook := <-l.flushHooks.newTransients:
1✔
1379
                        if l.channel.IsChannelClean() {
1✔
UNCOV
1380
                                hook()
×
1381
                        } else {
1✔
1382
                                l.flushHooks.alloc(hook)
1✔
1383
                        }
1✔
1384

1385
                // We have a new hook that needs to be run when we have
1386
                // committed all of our updates.
1387
                case hook := <-l.outgoingCommitHooks.newTransients:
1✔
1388
                        if !l.channel.OweCommitment() {
1✔
UNCOV
1389
                                hook()
×
1390
                        } else {
1✔
1391
                                l.outgoingCommitHooks.alloc(hook)
1✔
1392
                        }
1✔
1393

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

1403
                // Our update fee timer has fired, so we'll check the network
1404
                // fee to see if we should adjust our commitment fee.
1405
                case <-l.updateFeeTimer.C:
4✔
1406
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
4✔
1407

4✔
1408
                        // If we're not the initiator of the channel, don't we
4✔
1409
                        // don't control the fees, so we can ignore this.
4✔
1410
                        if !l.channel.IsInitiator() {
4✔
1411
                                continue
×
1412
                        }
1413

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

1424
                        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
4✔
1425

4✔
1426
                        newCommitFee := l.channel.IdealCommitFeeRate(
4✔
1427
                                netFee, minRelayFee,
4✔
1428
                                l.cfg.MaxAnchorsCommitFeeRate,
4✔
1429
                                l.cfg.MaxFeeAllocation,
4✔
1430
                        )
4✔
1431

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

1✔
1441
                                continue
1✔
1442
                        }
1443

1444
                        // If we do, then we'll send a new UpdateFee message to
1445
                        // the remote party, to be locked in with a new update.
1446
                        if err := l.updateChannelFee(newCommitFee); err != nil {
3✔
1447
                                l.log.Errorf("unable to update fee rate: %v",
×
1448
                                        err)
×
1449
                                continue
×
1450
                        }
1451

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

×
UNCOV
1461
                        // TODO(roasbeef): remove all together
×
UNCOV
1462
                        go func() {
×
UNCOV
1463
                                chanPoint := l.channel.ChannelPoint()
×
UNCOV
1464
                                l.cfg.Peer.WipeChannel(&chanPoint)
×
UNCOV
1465
                        }()
×
1466

UNCOV
1467
                        return
×
1468

1469
                case <-l.cfg.BatchTicker.Ticks():
192✔
1470
                        // Attempt to extend the remote commitment chain
192✔
1471
                        // including all the currently pending entries. If the
192✔
1472
                        // send was unsuccessful, then abandon the update,
192✔
1473
                        // waiting for the revocation window to open up.
192✔
1474
                        if !l.updateCommitTxOrFail() {
192✔
1475
                                return
×
1476
                        }
×
1477

1478
                case <-l.cfg.PendingCommitTicker.Ticks():
1✔
1479
                        l.failf(
1✔
1480
                                LinkFailureError{
1✔
1481
                                        code:          ErrRemoteUnresponsive,
1✔
1482
                                        FailureAction: LinkFailureDisconnect,
1✔
1483
                                },
1✔
1484
                                "unable to complete dance",
1✔
1485
                        )
1✔
1486
                        return
1✔
1487

1488
                // A message from the switch was just received. This indicates
1489
                // that the link is an intermediate hop in a multi-hop HTLC
1490
                // circuit.
1491
                case pkt := <-l.downstream:
521✔
1492
                        l.handleDownstreamPkt(pkt)
521✔
1493

1494
                // A message from the connected peer was just received. This
1495
                // indicates that we have a new incoming HTLC, either directly
1496
                // for us, or part of a multi-hop HTLC circuit.
1497
                case msg := <-l.upstream:
3,175✔
1498
                        l.handleUpstreamMsg(msg)
3,175✔
1499

1500
                // A htlc resolution is received. This means that we now have a
1501
                // resolution for a previously accepted htlc.
1502
                case hodlItem := <-l.hodlQueue.ChanOut():
55✔
1503
                        htlcResolution := hodlItem.(invoices.HtlcResolution)
55✔
1504
                        err := l.processHodlQueue(htlcResolution)
55✔
1505
                        switch err {
55✔
1506
                        // No error, success.
1507
                        case nil:
54✔
1508

1509
                        // If the duplicate keystone error was encountered,
1510
                        // fail back gracefully.
1511
                        case ErrDuplicateKeystone:
×
1512
                                l.failf(LinkFailureError{
×
1513
                                        code: ErrCircuitError,
×
1514
                                }, "process hodl queue: "+
×
1515
                                        "temporary circuit error: %v",
×
1516
                                        err,
×
1517
                                )
×
1518

1519
                        // Send an Error message to the peer.
1520
                        default:
1✔
1521
                                l.failf(LinkFailureError{
1✔
1522
                                        code: ErrInternalError,
1✔
1523
                                }, "process hodl queue: unable to update "+
1✔
1524
                                        "commitment: %v", err,
1✔
1525
                                )
1✔
1526
                        }
1527

1528
                case qReq := <-l.quiescenceReqs:
1✔
1529
                        l.quiescer.InitStfu(qReq)
1✔
1530

1✔
1531
                        if l.noDanglingUpdates(lntypes.Local) {
2✔
1532
                                err := l.quiescer.SendOwedStfu()
1✔
1533
                                if err != nil {
1✔
1534
                                        l.stfuFailf(
×
1535
                                                "SendOwedStfu: %s", err.Error(),
×
1536
                                        )
×
1537
                                        res := fn.Err[lntypes.ChannelParty](err)
×
1538
                                        qReq.Resolve(res)
×
1539
                                }
×
1540
                        }
1541

1542
                case <-l.Quit:
189✔
1543
                        return
189✔
1544
                }
1545
        }
1546
}
1547

1548
// processHodlQueue processes a received htlc resolution and continues reading
1549
// from the hodl queue until no more resolutions remain. When this function
1550
// returns without an error, the commit tx should be updated.
1551
func (l *channelLink) processHodlQueue(
1552
        firstResolution invoices.HtlcResolution) error {
55✔
1553

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

1567
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
55✔
1568
                        return err
×
1569
                }
×
1570

1571
                // Clean up hodl map.
1572
                delete(l.hodlMap, circuitKey)
55✔
1573

55✔
1574
                select {
55✔
UNCOV
1575
                case item := <-l.hodlQueue.ChanOut():
×
UNCOV
1576
                        htlcResolution = item.(invoices.HtlcResolution)
×
1577
                default:
55✔
1578
                        break loop
55✔
1579
                }
1580
        }
1581

1582
        // Update the commitment tx.
1583
        if err := l.updateCommitTx(); err != nil {
56✔
1584
                return err
1✔
1585
        }
1✔
1586

1587
        return nil
54✔
1588
}
1589

1590
// processHtlcResolution applies a received htlc resolution to the provided
1591
// htlc. When this function returns without an error, the commit tx should be
1592
// updated.
1593
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1594
        htlc hodlHtlc) error {
201✔
1595

201✔
1596
        circuitKey := resolution.CircuitKey()
201✔
1597

201✔
1598
        // Determine required action for the resolution based on the type of
201✔
1599
        // resolution we have received.
201✔
1600
        switch res := resolution.(type) {
201✔
1601
        // Settle htlcs that returned a settle resolution using the preimage
1602
        // in the resolution.
1603
        case *invoices.HtlcSettleResolution:
197✔
1604
                l.log.Debugf("received settle resolution for %v "+
197✔
1605
                        "with outcome: %v", circuitKey, res.Outcome)
197✔
1606

197✔
1607
                return l.settleHTLC(
197✔
1608
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
197✔
1609
                )
197✔
1610

1611
        // For htlc failures, we get the relevant failure message based
1612
        // on the failure resolution and then fail the htlc.
1613
        case *invoices.HtlcFailResolution:
4✔
1614
                l.log.Debugf("received cancel resolution for "+
4✔
1615
                        "%v with outcome: %v", circuitKey, res.Outcome)
4✔
1616

4✔
1617
                // Get the lnwire failure message based on the resolution
4✔
1618
                // result.
4✔
1619
                failure := getResolutionFailure(res, htlc.add.Amount)
4✔
1620

4✔
1621
                l.sendHTLCError(
4✔
1622
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
4✔
1623
                        true,
4✔
1624
                )
4✔
1625
                return nil
4✔
1626

1627
        // Fail if we do not get a settle of fail resolution, since we
1628
        // are only expecting to handle settles and fails.
1629
        default:
×
1630
                return fmt.Errorf("unknown htlc resolution type: %T",
×
1631
                        resolution)
×
1632
        }
1633
}
1634

1635
// getResolutionFailure returns the wire message that a htlc resolution should
1636
// be failed with.
1637
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1638
        amount lnwire.MilliSatoshi) *LinkError {
4✔
1639

4✔
1640
        // If the resolution has been resolved as part of a MPP timeout,
4✔
1641
        // we need to fail the htlc with lnwire.FailMppTimeout.
4✔
1642
        if resolution.Outcome == invoices.ResultMppTimeout {
4✔
1643
                return NewDetailedLinkError(
×
1644
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
1645
                )
×
1646
        }
×
1647

1648
        // If the htlc is not a MPP timeout, we fail it with
1649
        // FailIncorrectDetails. This error is sent for invoice payment
1650
        // failures such as underpayment/ expiry too soon and hodl invoices
1651
        // (which return FailIncorrectDetails to avoid leaking information).
1652
        incorrectDetails := lnwire.NewFailIncorrectDetails(
4✔
1653
                amount, uint32(resolution.AcceptHeight),
4✔
1654
        )
4✔
1655

4✔
1656
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
4✔
1657
}
1658

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

1668
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1669
// downstream HTLC Switch.
1670
func (l *channelLink) handleDownstreamUpdateAdd(pkt *htlcPacket) error {
480✔
1671
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
480✔
1672
        if !ok {
480✔
1673
                return errors.New("not an UpdateAddHTLC packet")
×
1674
        }
×
1675

1676
        // If we are flushing the link in the outgoing direction or we have
1677
        // already sent Stfu, then we can't add new htlcs to the link and we
1678
        // need to bounce it.
1679
        if l.IsFlushing(Outgoing) || !l.quiescer.CanSendUpdates() {
480✔
1680
                l.mailBox.FailAdd(pkt)
×
1681

×
1682
                return NewDetailedLinkError(
×
1683
                        &lnwire.FailTemporaryChannelFailure{},
×
1684
                        OutgoingFailureLinkNotEligible,
×
1685
                )
×
1686
        }
×
1687

1688
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1689
        // arbitrary delays between the switch adding an ADD to the
1690
        // mailbox, and the HTLC being added to the commitment state.
1691
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
480✔
1692
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
1693
                l.mailBox.AckPacket(pkt.inKey())
×
1694
                return nil
×
1695
        }
×
1696

1697
        // Check if we can add the HTLC here without exceededing the max fee
1698
        // exposure threshold.
1699
        if l.isOverexposedWithHtlc(htlc, false) {
484✔
1700
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1701
                        "exposure exceeded")
4✔
1702

4✔
1703
                l.mailBox.FailAdd(pkt)
4✔
1704

4✔
1705
                return NewDetailedLinkError(
4✔
1706
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1707
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1708
                )
4✔
1709
        }
4✔
1710

1711
        // A new payment has been initiated via the downstream channel,
1712
        // so we add the new HTLC to our local log, then update the
1713
        // commitment chains.
1714
        htlc.ChanID = l.ChanID()
476✔
1715
        openCircuitRef := pkt.inKey()
476✔
1716

476✔
1717
        // We enforce the fee buffer for the commitment transaction because
476✔
1718
        // we are in control of adding this htlc. Nothing has locked-in yet so
476✔
1719
        // we can securely enforce the fee buffer which is only relevant if we
476✔
1720
        // are the initiator of the channel.
476✔
1721
        index, err := l.channel.AddHTLC(htlc, &openCircuitRef)
476✔
1722
        if err != nil {
477✔
1723
                // The HTLC was unable to be added to the state machine,
1✔
1724
                // as a result, we'll signal the switch to cancel the
1✔
1725
                // pending payment.
1✔
1726
                l.log.Warnf("Unable to handle downstream add HTLC: %v",
1✔
1727
                        err)
1✔
1728

1✔
1729
                // Remove this packet from the link's mailbox, this
1✔
1730
                // prevents it from being reprocessed if the link
1✔
1731
                // restarts and resets it mailbox. If this response
1✔
1732
                // doesn't make it back to the originating link, it will
1✔
1733
                // be rejected upon attempting to reforward the Add to
1✔
1734
                // the switch, since the circuit was never fully opened,
1✔
1735
                // and the forwarding package shows it as
1✔
1736
                // unacknowledged.
1✔
1737
                l.mailBox.FailAdd(pkt)
1✔
1738

1✔
1739
                return NewDetailedLinkError(
1✔
1740
                        lnwire.NewTemporaryChannelFailure(nil),
1✔
1741
                        OutgoingFailureDownstreamHtlcAdd,
1✔
1742
                )
1✔
1743
        }
1✔
1744

1745
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
475✔
1746
                "local_log_index=%v, pend_updates=%v",
475✔
1747
                htlc.PaymentHash[:], index,
475✔
1748
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
475✔
1749

475✔
1750
        pkt.outgoingChanID = l.ShortChanID()
475✔
1751
        pkt.outgoingHTLCID = index
475✔
1752
        htlc.ID = index
475✔
1753

475✔
1754
        l.log.Debugf("queueing keystone of ADD open circuit: %s->%s",
475✔
1755
                pkt.inKey(), pkt.outKey())
475✔
1756

475✔
1757
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
475✔
1758
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
475✔
1759

475✔
1760
        _ = l.cfg.Peer.SendMessage(false, htlc)
475✔
1761

475✔
1762
        // Send a forward event notification to htlcNotifier.
475✔
1763
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
475✔
1764
                newHtlcKey(pkt),
475✔
1765
                HtlcInfo{
475✔
1766
                        IncomingTimeLock: pkt.incomingTimeout,
475✔
1767
                        IncomingAmt:      pkt.incomingAmount,
475✔
1768
                        OutgoingTimeLock: htlc.Expiry,
475✔
1769
                        OutgoingAmt:      htlc.Amount,
475✔
1770
                },
475✔
1771
                getEventType(pkt),
475✔
1772
        )
475✔
1773

475✔
1774
        l.tryBatchUpdateCommitTx()
475✔
1775

475✔
1776
        return nil
475✔
1777
}
1778

1779
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1780
// Switch. Possible messages sent by the switch include requests to forward new
1781
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1782
// cleared HTLCs with the upstream peer.
1783
//
1784
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1785
func (l *channelLink) handleDownstreamPkt(pkt *htlcPacket) {
521✔
1786
        if pkt.htlc.MsgType().IsChannelUpdate() &&
521✔
1787
                !l.quiescer.CanSendUpdates() {
521✔
1788

×
1789
                l.log.Warnf("unable to process channel update. "+
×
1790
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1791

×
1792
                return
×
1793
        }
×
1794

1795
        switch htlc := pkt.htlc.(type) {
521✔
1796
        case *lnwire.UpdateAddHTLC:
480✔
1797
                // Handle add message. The returned error can be ignored,
480✔
1798
                // because it is also sent through the mailbox.
480✔
1799
                _ = l.handleDownstreamUpdateAdd(pkt)
480✔
1800

1801
        case *lnwire.UpdateFulfillHTLC:
23✔
1802
                // If hodl.SettleOutgoing mode is active, we exit early to
23✔
1803
                // simulate arbitrary delays between the switch adding the
23✔
1804
                // SETTLE to the mailbox, and the HTLC being added to the
23✔
1805
                // commitment state.
23✔
1806
                if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
23✔
1807
                        l.log.Warnf(hodl.SettleOutgoing.Warning())
×
1808
                        l.mailBox.AckPacket(pkt.inKey())
×
1809
                        return
×
1810
                }
×
1811

1812
                // An HTLC we forward to the switch has just settled somewhere
1813
                // upstream. Therefore we settle the HTLC within the our local
1814
                // state machine.
1815
                inKey := pkt.inKey()
23✔
1816
                err := l.channel.SettleHTLC(
23✔
1817
                        htlc.PaymentPreimage,
23✔
1818
                        pkt.incomingHTLCID,
23✔
1819
                        pkt.sourceRef,
23✔
1820
                        pkt.destRef,
23✔
1821
                        &inKey,
23✔
1822
                )
23✔
1823
                if err != nil {
23✔
1824
                        l.log.Errorf("unable to settle incoming HTLC for "+
×
1825
                                "circuit-key=%v: %v", inKey, err)
×
1826

×
1827
                        // If the HTLC index for Settle response was not known
×
1828
                        // to our commitment state, it has already been
×
1829
                        // cleaned up by a prior response. We'll thus try to
×
1830
                        // clean up any lingering state to ensure we don't
×
1831
                        // continue reforwarding.
×
1832
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
×
1833
                                l.cleanupSpuriousResponse(pkt)
×
1834
                        }
×
1835

1836
                        // Remove the packet from the link's mailbox to ensure
1837
                        // it doesn't get replayed after a reconnection.
1838
                        l.mailBox.AckPacket(inKey)
×
1839

×
1840
                        return
×
1841
                }
1842

1843
                l.log.Debugf("queueing removal of SETTLE closed circuit: "+
23✔
1844
                        "%s->%s", pkt.inKey(), pkt.outKey())
23✔
1845

23✔
1846
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
23✔
1847

23✔
1848
                // With the HTLC settled, we'll need to populate the wire
23✔
1849
                // message to target the specific channel and HTLC to be
23✔
1850
                // canceled.
23✔
1851
                htlc.ChanID = l.ChanID()
23✔
1852
                htlc.ID = pkt.incomingHTLCID
23✔
1853

23✔
1854
                // Then we send the HTLC settle message to the connected peer
23✔
1855
                // so we can continue the propagation of the settle message.
23✔
1856
                l.cfg.Peer.SendMessage(false, htlc)
23✔
1857

23✔
1858
                // Send a settle event notification to htlcNotifier.
23✔
1859
                l.cfg.HtlcNotifier.NotifySettleEvent(
23✔
1860
                        newHtlcKey(pkt),
23✔
1861
                        htlc.PaymentPreimage,
23✔
1862
                        getEventType(pkt),
23✔
1863
                )
23✔
1864

23✔
1865
                // Immediately update the commitment tx to minimize latency.
23✔
1866
                l.updateCommitTxOrFail()
23✔
1867

1868
        case *lnwire.UpdateFailHTLC:
18✔
1869
                // If hodl.FailOutgoing mode is active, we exit early to
18✔
1870
                // simulate arbitrary delays between the switch adding a FAIL to
18✔
1871
                // the mailbox, and the HTLC being added to the commitment
18✔
1872
                // state.
18✔
1873
                if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
18✔
1874
                        l.log.Warnf(hodl.FailOutgoing.Warning())
×
1875
                        l.mailBox.AckPacket(pkt.inKey())
×
1876
                        return
×
1877
                }
×
1878

1879
                // An HTLC cancellation has been triggered somewhere upstream,
1880
                // we'll remove then HTLC from our local state machine.
1881
                inKey := pkt.inKey()
18✔
1882
                err := l.channel.FailHTLC(
18✔
1883
                        pkt.incomingHTLCID,
18✔
1884
                        htlc.Reason,
18✔
1885
                        pkt.sourceRef,
18✔
1886
                        pkt.destRef,
18✔
1887
                        &inKey,
18✔
1888
                )
18✔
1889
                if err != nil {
20✔
1890
                        l.log.Errorf("unable to cancel incoming HTLC for "+
2✔
1891
                                "circuit-key=%v: %v", inKey, err)
2✔
1892

2✔
1893
                        // If the HTLC index for Fail response was not known to
2✔
1894
                        // our commitment state, it has already been cleaned up
2✔
1895
                        // by a prior response. We'll thus try to clean up any
2✔
1896
                        // lingering state to ensure we don't continue
2✔
1897
                        // reforwarding.
2✔
1898
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
4✔
1899
                                l.cleanupSpuriousResponse(pkt)
2✔
1900
                        }
2✔
1901

1902
                        // Remove the packet from the link's mailbox to ensure
1903
                        // it doesn't get replayed after a reconnection.
1904
                        l.mailBox.AckPacket(inKey)
2✔
1905

2✔
1906
                        return
2✔
1907
                }
1908

1909
                l.log.Debugf("queueing removal of FAIL closed circuit: %s->%s",
16✔
1910
                        pkt.inKey(), pkt.outKey())
16✔
1911

16✔
1912
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
16✔
1913

16✔
1914
                // With the HTLC removed, we'll need to populate the wire
16✔
1915
                // message to target the specific channel and HTLC to be
16✔
1916
                // canceled. The "Reason" field will have already been set
16✔
1917
                // within the switch.
16✔
1918
                htlc.ChanID = l.ChanID()
16✔
1919
                htlc.ID = pkt.incomingHTLCID
16✔
1920

16✔
1921
                // We send the HTLC message to the peer which initially created
16✔
1922
                // the HTLC. If the incoming blinding point is non-nil, we
16✔
1923
                // know that we are a relaying node in a blinded path.
16✔
1924
                // Otherwise, we're either an introduction node or not part of
16✔
1925
                // a blinded path at all.
16✔
1926
                if err := l.sendIncomingHTLCFailureMsg(
16✔
1927
                        htlc.ID,
16✔
1928
                        pkt.obfuscator,
16✔
1929
                        htlc.Reason,
16✔
1930
                ); err != nil {
16✔
1931
                        l.log.Errorf("unable to send HTLC failure: %v",
×
1932
                                err)
×
1933

×
1934
                        return
×
1935
                }
×
1936

1937
                // If the packet does not have a link failure set, it failed
1938
                // further down the route so we notify a forwarding failure.
1939
                // Otherwise, we notify a link failure because it failed at our
1940
                // node.
1941
                if pkt.linkFailure != nil {
26✔
1942
                        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
10✔
1943
                                newHtlcKey(pkt),
10✔
1944
                                newHtlcInfo(pkt),
10✔
1945
                                getEventType(pkt),
10✔
1946
                                pkt.linkFailure,
10✔
1947
                                false,
10✔
1948
                        )
10✔
1949
                } else {
16✔
1950
                        l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
6✔
1951
                                newHtlcKey(pkt), getEventType(pkt),
6✔
1952
                        )
6✔
1953
                }
6✔
1954

1955
                // Immediately update the commitment tx to minimize latency.
1956
                l.updateCommitTxOrFail()
16✔
1957
        }
1958
}
1959

1960
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1961
// full.
1962
func (l *channelLink) tryBatchUpdateCommitTx() {
475✔
1963
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
475✔
1964
        if pending < uint64(l.cfg.BatchSize) {
934✔
1965
                return
459✔
1966
        }
459✔
1967

1968
        l.updateCommitTxOrFail()
16✔
1969
}
1970

1971
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1972
// associated with this packet. If successful in doing so, it will also purge
1973
// the open circuit from the circuit map and remove the packet from the link's
1974
// mailbox.
1975
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
2✔
1976
        inKey := pkt.inKey()
2✔
1977

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

2✔
1981
        // If the htlc packet doesn't have a source reference, it is unsafe to
2✔
1982
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
2✔
1983
        if pkt.sourceRef == nil {
3✔
1984
                l.log.Errorf("unable to cleanup response for incoming "+
1✔
1985
                        "circuit-key=%v, does not contain source reference",
1✔
1986
                        inKey)
1✔
1987
                return
1✔
1988
        }
1✔
1989

1990
        // If the source reference is present,  we will try to prevent this link
1991
        // from resending the packet to the switch. To do so, we ack the AddRef
1992
        // of the incoming HTLC belonging to this link.
1993
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
1✔
1994
        if err != nil {
1✔
1995
                l.log.Errorf("unable to ack AddRef for incoming "+
×
1996
                        "circuit-key=%v: %v", inKey, err)
×
1997

×
1998
                // If this operation failed, it is unsafe to attempt removal of
×
1999
                // the destination reference or circuit, so we exit early. The
×
2000
                // cleanup may proceed with a different packet in the future
×
2001
                // that succeeds on this step.
×
2002
                return
×
2003
        }
×
2004

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

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

1✔
2026
        // With all known references acked, we can now safely delete the circuit
1✔
2027
        // from the switch's circuit map, as the state is no longer needed.
1✔
2028
        err = l.cfg.Circuits.DeleteCircuits(inKey)
1✔
2029
        if err != nil {
1✔
2030
                l.log.Errorf("unable to delete circuit for "+
×
2031
                        "circuit-key=%v: %v", inKey, err)
×
2032
        }
×
2033
}
2034

2035
// handleUpstreamMsg processes wire messages related to commitment state
2036
// updates from the upstream peer. The upstream peer is the peer whom we have a
2037
// direct channel with, updating our respective commitment chains.
2038
func (l *channelLink) handleUpstreamMsg(msg lnwire.Message) {
3,175✔
2039
        // First check if the message is an update and we are capable of
3,175✔
2040
        // receiving updates right now.
3,175✔
2041
        if msg.MsgType().IsChannelUpdate() && !l.quiescer.CanRecvUpdates() {
3,175✔
2042
                l.stfuFailf("update received after stfu: %T", msg)
×
2043
                return
×
2044
        }
×
2045

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

×
2078
                        return
×
2079
                }
×
2080

2081
                // Disallow htlcs with blinding points set if we haven't
2082
                // enabled the feature. This saves us from having to process
2083
                // the onion at all, but will only catch blinded payments
2084
                // where we are a relaying node (as the blinding point will
2085
                // be in the payload when we're the introduction node).
2086
                if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
450✔
2087
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2088
                                "blinding point included when route blinding "+
×
2089
                                        "is disabled")
×
2090

×
2091
                        return
×
2092
                }
×
2093

2094
                // We have to check the limit here rather than later in the
2095
                // switch because the counterparty can keep sending HTLC's
2096
                // without sending a revoke. This would mean that the switch
2097
                // check would only occur later.
2098
                if l.isOverexposedWithHtlc(msg, true) {
450✔
2099
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2100
                                "peer sent us an HTLC that exceeded our max "+
×
2101
                                        "fee exposure")
×
2102

×
2103
                        return
×
2104
                }
×
2105

2106
                // We just received an add request from an upstream peer, so we
2107
                // add it to our state machine, then add the HTLC to our
2108
                // "settle" list in the event that we know the preimage.
2109
                index, err := l.channel.ReceiveHTLC(msg)
450✔
2110
                if err != nil {
450✔
2111
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2112
                                "unable to handle upstream add HTLC: %v", err)
×
2113
                        return
×
2114
                }
×
2115

2116
                l.log.Tracef("receive upstream htlc with payment hash(%x), "+
450✔
2117
                        "assigning index: %v", msg.PaymentHash[:], index)
450✔
2118

2119
        case *lnwire.UpdateFulfillHTLC:
227✔
2120
                pre := msg.PaymentPreimage
227✔
2121
                idx := msg.ID
227✔
2122

227✔
2123
                // Before we pipeline the settle, we'll check the set of active
227✔
2124
                // htlc's to see if the related UpdateAddHTLC has been fully
227✔
2125
                // locked-in.
227✔
2126
                var lockedin bool
227✔
2127
                htlcs := l.channel.ActiveHtlcs()
227✔
2128
                for _, add := range htlcs {
1,088✔
2129
                        // The HTLC will be outgoing and match idx.
861✔
2130
                        if !add.Incoming && add.HtlcIndex == idx {
1,086✔
2131
                                lockedin = true
225✔
2132
                                break
225✔
2133
                        }
2134
                }
2135

2136
                if !lockedin {
229✔
2137
                        l.failf(
2✔
2138
                                LinkFailureError{code: ErrInvalidUpdate},
2✔
2139
                                "unable to handle upstream settle",
2✔
2140
                        )
2✔
2141
                        return
2✔
2142
                }
2✔
2143

2144
                if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
225✔
UNCOV
2145
                        l.failf(
×
UNCOV
2146
                                LinkFailureError{
×
UNCOV
2147
                                        code:          ErrInvalidUpdate,
×
UNCOV
2148
                                        FailureAction: LinkFailureForceClose,
×
UNCOV
2149
                                },
×
UNCOV
2150
                                "unable to handle upstream settle HTLC: %v", err,
×
UNCOV
2151
                        )
×
UNCOV
2152
                        return
×
UNCOV
2153
                }
×
2154

2155
                settlePacket := &htlcPacket{
225✔
2156
                        outgoingChanID: l.ShortChanID(),
225✔
2157
                        outgoingHTLCID: idx,
225✔
2158
                        htlc: &lnwire.UpdateFulfillHTLC{
225✔
2159
                                PaymentPreimage: pre,
225✔
2160
                        },
225✔
2161
                }
225✔
2162

225✔
2163
                // Add the newly discovered preimage to our growing list of
225✔
2164
                // uncommitted preimage. These will be written to the witness
225✔
2165
                // cache just before accepting the next commitment signature
225✔
2166
                // from the remote peer.
225✔
2167
                l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
225✔
2168

225✔
2169
                // Pipeline this settle, send it to the switch.
225✔
2170
                go l.forwardBatch(false, settlePacket)
225✔
2171

2172
        case *lnwire.UpdateFailMalformedHTLC:
3✔
2173
                // Convert the failure type encoded within the HTLC fail
3✔
2174
                // message to the proper generic lnwire error code.
3✔
2175
                var failure lnwire.FailureMessage
3✔
2176
                switch msg.FailureCode {
3✔
2177
                case lnwire.CodeInvalidOnionVersion:
1✔
2178
                        failure = &lnwire.FailInvalidOnionVersion{
1✔
2179
                                OnionSHA256: msg.ShaOnionBlob,
1✔
2180
                        }
1✔
2181
                case lnwire.CodeInvalidOnionHmac:
×
2182
                        failure = &lnwire.FailInvalidOnionHmac{
×
2183
                                OnionSHA256: msg.ShaOnionBlob,
×
2184
                        }
×
2185

2186
                case lnwire.CodeInvalidOnionKey:
×
2187
                        failure = &lnwire.FailInvalidOnionKey{
×
2188
                                OnionSHA256: msg.ShaOnionBlob,
×
2189
                        }
×
2190

2191
                // Handle malformed errors that are part of a blinded route.
2192
                // This case is slightly different, because we expect every
2193
                // relaying node in the blinded portion of the route to send
2194
                // malformed errors. If we're also a relaying node, we're
2195
                // likely going to switch this error out anyway for our own
2196
                // malformed error, but we handle the case here for
2197
                // completeness.
UNCOV
2198
                case lnwire.CodeInvalidBlinding:
×
UNCOV
2199
                        failure = &lnwire.FailInvalidBlinding{
×
UNCOV
2200
                                OnionSHA256: msg.ShaOnionBlob,
×
UNCOV
2201
                        }
×
2202

2203
                default:
2✔
2204
                        l.log.Warnf("unexpected failure code received in "+
2✔
2205
                                "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
2206

2✔
2207
                        // We don't just pass back the error we received from
2✔
2208
                        // our successor. Otherwise we might report a failure
2✔
2209
                        // that penalizes us more than needed. If the onion that
2✔
2210
                        // we forwarded was correct, the node should have been
2✔
2211
                        // able to send back its own failure. The node did not
2✔
2212
                        // send back its own failure, so we assume there was a
2✔
2213
                        // problem with the onion and report that back. We reuse
2✔
2214
                        // the invalid onion key failure because there is no
2✔
2215
                        // specific error for this case.
2✔
2216
                        failure = &lnwire.FailInvalidOnionKey{
2✔
2217
                                OnionSHA256: msg.ShaOnionBlob,
2✔
2218
                        }
2✔
2219
                }
2220

2221
                // With the error parsed, we'll convert the into it's opaque
2222
                // form.
2223
                var b bytes.Buffer
3✔
2224
                if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
3✔
2225
                        l.log.Errorf("unable to encode malformed error: %v", err)
×
2226
                        return
×
2227
                }
×
2228

2229
                // If remote side have been unable to parse the onion blob we
2230
                // have sent to it, than we should transform the malformed HTLC
2231
                // message to the usual HTLC fail message.
2232
                err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
3✔
2233
                if err != nil {
3✔
2234
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2235
                                "unable to handle upstream fail HTLC: %v", err)
×
2236
                        return
×
2237
                }
×
2238

2239
        case *lnwire.UpdateFailHTLC:
120✔
2240
                // Verify that the failure reason is at least 256 bytes plus
120✔
2241
                // overhead.
120✔
2242
                const minimumFailReasonLength = lnwire.FailureMessageLength +
120✔
2243
                        2 + 2 + 32
120✔
2244

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

×
2264
                                return
×
2265
                        }
×
2266
                }
2267

2268
                // Add fail to the update log.
2269
                idx := msg.ID
120✔
2270
                err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
120✔
2271
                if err != nil {
120✔
2272
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2273
                                "unable to handle upstream fail HTLC: %v", err)
×
2274
                        return
×
2275
                }
×
2276

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

2299
                // Instead of truncating the slice to conserve memory
2300
                // allocations, we simply set the uncommitted preimage slice to
2301
                // nil so that a new one will be initialized if any more
2302
                // witnesses are discovered. We do this because the maximum size
2303
                // that the slice can occupy is 15KB, and we want to ensure we
2304
                // release that memory back to the runtime.
2305
                l.uncommittedPreimages = nil
1,190✔
2306

1,190✔
2307
                // We just received a new updates to our local commitment
1,190✔
2308
                // chain, validate this new commitment, closing the link if
1,190✔
2309
                // invalid.
1,190✔
2310
                auxSigBlob, err := msg.CustomRecords.Serialize()
1,190✔
2311
                if err != nil {
1,190✔
2312
                        l.failf(
×
2313
                                LinkFailureError{code: ErrInvalidCommitment},
×
2314
                                "unable to serialize custom records: %v", err,
×
2315
                        )
×
2316

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

2350
                // As we've just accepted a new state, we'll now
2351
                // immediately send the remote peer a revocation for our prior
2352
                // state.
2353
                nextRevocation, currentHtlcs, finalHTLCs, err :=
1,190✔
2354
                        l.channel.RevokeCurrentCommitment()
1,190✔
2355
                if err != nil {
1,190✔
2356
                        l.log.Errorf("unable to revoke commitment: %v", err)
×
2357

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

2379
                // As soon as we are ready to send our next revocation, we can
2380
                // invoke the incoming commit hooks.
2381
                l.RWMutex.Lock()
1,190✔
2382
                l.incomingCommitHooks.invoke()
1,190✔
2383
                l.RWMutex.Unlock()
1,190✔
2384

1,190✔
2385
                l.cfg.Peer.SendMessage(false, nextRevocation)
1,190✔
2386

1,190✔
2387
                // Notify the incoming htlcs of which the resolutions were
1,190✔
2388
                // locked in.
1,190✔
2389
                for id, settled := range finalHTLCs {
1,521✔
2390
                        l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
331✔
2391
                                models.CircuitKey{
331✔
2392
                                        ChanID: l.ShortChanID(),
331✔
2393
                                        HtlcID: id,
331✔
2394
                                },
331✔
2395
                                channeldb.FinalHtlcInfo{
331✔
2396
                                        Settled:  settled,
331✔
2397
                                        Offchain: true,
331✔
2398
                                },
331✔
2399
                        )
331✔
2400
                }
331✔
2401

2402
                // Since we just revoked our commitment, we may have a new set
2403
                // of HTLC's on our commitment, so we'll send them using our
2404
                // function closure NotifyContractUpdate.
2405
                newUpdate := &contractcourt.ContractUpdate{
1,190✔
2406
                        HtlcKey: contractcourt.LocalHtlcSet,
1,190✔
2407
                        Htlcs:   currentHtlcs,
1,190✔
2408
                }
1,190✔
2409
                err = l.cfg.NotifyContractUpdate(newUpdate)
1,190✔
2410
                if err != nil {
1,190✔
2411
                        l.log.Errorf("unable to notify contract update: %v",
×
2412
                                err)
×
2413
                        return
×
2414
                }
×
2415

2416
                select {
1,190✔
2417
                case <-l.Quit:
×
2418
                        return
×
2419
                default:
1,190✔
2420
                }
2421

2422
                // If the remote party initiated the state transition,
2423
                // we'll reply with a signature to provide them with their
2424
                // version of the latest commitment. Otherwise, both commitment
2425
                // chains are fully synced from our PoV, then we don't need to
2426
                // reply with a signature as both sides already have a
2427
                // commitment with the latest accepted.
2428
                if l.channel.OweCommitment() {
1,858✔
2429
                        if !l.updateCommitTxOrFail() {
668✔
2430
                                return
×
2431
                        }
×
2432
                }
2433

2434
                // If we need to send out an Stfu, this would be the time to do
2435
                // so.
2436
                if l.noDanglingUpdates(lntypes.Local) {
2,236✔
2437
                        err = l.quiescer.SendOwedStfu()
1,046✔
2438
                        if err != nil {
1,046✔
2439
                                l.stfuFailf("sendOwedStfu: %v", err.Error())
×
2440
                        }
×
2441
                }
2442

2443
                // Now that we have finished processing the incoming CommitSig
2444
                // and sent out our RevokeAndAck, we invoke the flushHooks if
2445
                // the channel state is clean.
2446
                l.RWMutex.Lock()
1,190✔
2447
                if l.channel.IsChannelClean() {
1,359✔
2448
                        l.flushHooks.invoke()
169✔
2449
                }
169✔
2450
                l.RWMutex.Unlock()
1,190✔
2451

2452
        case *lnwire.RevokeAndAck:
1,179✔
2453
                // We've received a revocation from the remote chain, if valid,
1,179✔
2454
                // this moves the remote chain forward, and expands our
1,179✔
2455
                // revocation window.
1,179✔
2456

1,179✔
2457
                // We now process the message and advance our remote commit
1,179✔
2458
                // chain.
1,179✔
2459
                fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
1,179✔
2460
                if err != nil {
1,179✔
2461
                        // TODO(halseth): force close?
×
2462
                        l.failf(
×
2463
                                LinkFailureError{
×
2464
                                        code:          ErrInvalidRevocation,
×
2465
                                        FailureAction: LinkFailureDisconnect,
×
2466
                                },
×
2467
                                "unable to accept revocation: %v", err,
×
2468
                        )
×
2469
                        return
×
2470
                }
×
2471

2472
                // The remote party now has a new primary commitment, so we'll
2473
                // update the contract court to be aware of this new set (the
2474
                // prior old remote pending).
2475
                newUpdate := &contractcourt.ContractUpdate{
1,179✔
2476
                        HtlcKey: contractcourt.RemoteHtlcSet,
1,179✔
2477
                        Htlcs:   remoteHTLCs,
1,179✔
2478
                }
1,179✔
2479
                err = l.cfg.NotifyContractUpdate(newUpdate)
1,179✔
2480
                if err != nil {
1,179✔
2481
                        l.log.Errorf("unable to notify contract update: %v",
×
2482
                                err)
×
2483
                        return
×
2484
                }
×
2485

2486
                select {
1,179✔
2487
                case <-l.Quit:
2✔
2488
                        return
2✔
2489
                default:
1,177✔
2490
                }
2491

2492
                // If we have a tower client for this channel type, we'll
2493
                // create a backup for the current state.
2494
                if l.cfg.TowerClient != nil {
1,177✔
UNCOV
2495
                        state := l.channel.State()
×
UNCOV
2496
                        chanID := l.ChanID()
×
UNCOV
2497

×
UNCOV
2498
                        err = l.cfg.TowerClient.BackupState(
×
UNCOV
2499
                                &chanID, state.RemoteCommitment.CommitHeight-1,
×
UNCOV
2500
                        )
×
UNCOV
2501
                        if err != nil {
×
2502
                                l.failf(LinkFailureError{
×
2503
                                        code: ErrInternalError,
×
2504
                                }, "unable to queue breach backup: %v", err)
×
2505
                                return
×
2506
                        }
×
2507
                }
2508

2509
                // If we can send updates then we can process adds in case we
2510
                // are the exit hop and need to send back resolutions, or in
2511
                // case there are validity issues with the packets. Otherwise
2512
                // we defer the action until resume.
2513
                //
2514
                // We are free to process the settles and fails without this
2515
                // check since processing those can't result in further updates
2516
                // to this channel link.
2517
                if l.quiescer.CanSendUpdates() {
2,353✔
2518
                        l.processRemoteAdds(fwdPkg)
1,176✔
2519
                } else {
1,177✔
2520
                        l.quiescer.OnResume(func() {
1✔
2521
                                l.processRemoteAdds(fwdPkg)
×
2522
                        })
×
2523
                }
2524
                l.processRemoteSettleFails(fwdPkg)
1,177✔
2525

1,177✔
2526
                // If the link failed during processing the adds, we must
1,177✔
2527
                // return to ensure we won't attempted to update the state
1,177✔
2528
                // further.
1,177✔
2529
                if l.failed {
1,177✔
UNCOV
2530
                        return
×
UNCOV
2531
                }
×
2532

2533
                // The revocation window opened up. If there are pending local
2534
                // updates, try to update the commit tx. Pending updates could
2535
                // already have been present because of a previously failed
2536
                // update to the commit tx or freshly added in by
2537
                // processRemoteAdds. Also in case there are no local updates,
2538
                // but there are still remote updates that are not in the remote
2539
                // commit tx yet, send out an update.
2540
                if l.channel.OweCommitment() {
1,485✔
2541
                        if !l.updateCommitTxOrFail() {
315✔
2542
                                return
7✔
2543
                        }
7✔
2544
                }
2545

2546
                // Now that we have finished processing the RevokeAndAck, we
2547
                // can invoke the flushHooks if the channel state is clean.
2548
                l.RWMutex.Lock()
1,170✔
2549
                if l.channel.IsChannelClean() {
1,329✔
2550
                        l.flushHooks.invoke()
159✔
2551
                }
159✔
2552
                l.RWMutex.Unlock()
1,170✔
2553

2554
        case *lnwire.UpdateFee:
3✔
2555
                // Check and see if their proposed fee-rate would make us
3✔
2556
                // exceed the fee threshold.
3✔
2557
                fee := chainfee.SatPerKWeight(msg.FeePerKw)
3✔
2558

3✔
2559
                isDust, err := l.exceedsFeeExposureLimit(fee)
3✔
2560
                if err != nil {
3✔
2561
                        // This shouldn't typically happen. If it does, it
×
2562
                        // indicates something is wrong with our channel state.
×
2563
                        l.log.Errorf("Unable to determine if fee threshold " +
×
2564
                                "exceeded")
×
2565
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2566
                                "error calculating fee exposure: %v", err)
×
2567

×
2568
                        return
×
2569
                }
×
2570

2571
                if isDust {
3✔
2572
                        // The proposed fee-rate makes us exceed the fee
×
2573
                        // threshold.
×
2574
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2575
                                "fee threshold exceeded: %v", err)
×
2576
                        return
×
2577
                }
×
2578

2579
                // We received fee update from peer. If we are the initiator we
2580
                // will fail the channel, if not we will apply the update.
2581
                if err := l.channel.ReceiveUpdateFee(fee); err != nil {
3✔
2582
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2583
                                "error receiving fee update: %v", err)
×
2584
                        return
×
2585
                }
×
2586

2587
                // Update the mailbox's feerate as well.
2588
                l.mailBox.SetFeeRate(fee)
3✔
2589

2590
        case *lnwire.Stfu:
2✔
2591
                err := l.handleStfu(msg)
2✔
2592
                if err != nil {
2✔
2593
                        l.stfuFailf("handleStfu: %v", err.Error())
×
2594
                }
×
2595

2596
        // In the case where we receive a warning message from our peer, just
2597
        // log it and move on. We choose not to disconnect from our peer,
2598
        // although we "MAY" do so according to the specification.
2599
        case *lnwire.Warning:
1✔
2600
                l.log.Warnf("received warning message from peer: %v",
1✔
2601
                        msg.Warning())
1✔
2602

UNCOV
2603
        case *lnwire.Error:
×
UNCOV
2604
                // Error received from remote, MUST fail channel, but should
×
UNCOV
2605
                // only print the contents of the error message if all
×
UNCOV
2606
                // characters are printable ASCII.
×
UNCOV
2607
                l.failf(
×
UNCOV
2608
                        LinkFailureError{
×
UNCOV
2609
                                code: ErrRemoteError,
×
UNCOV
2610

×
UNCOV
2611
                                // TODO(halseth): we currently don't fail the
×
UNCOV
2612
                                // channel permanently, as there are some sync
×
UNCOV
2613
                                // issues with other implementations that will
×
UNCOV
2614
                                // lead to them sending an error message, but
×
UNCOV
2615
                                // we can recover from on next connection. See
×
UNCOV
2616
                                // https://github.com/ElementsProject/lightning/issues/4212
×
UNCOV
2617
                                PermanentFailure: false,
×
UNCOV
2618
                        },
×
UNCOV
2619
                        "ChannelPoint(%v): received error from peer: %v",
×
UNCOV
2620
                        l.channel.ChannelPoint(), msg.Error(),
×
UNCOV
2621
                )
×
2622
        default:
×
2623
                l.log.Warnf("received unknown message of type %T", msg)
×
2624
        }
2625

2626
}
2627

2628
// handleStfu implements the top-level logic for handling the Stfu message from
2629
// our peer.
2630
func (l *channelLink) handleStfu(stfu *lnwire.Stfu) error {
2✔
2631
        if !l.noDanglingUpdates(lntypes.Remote) {
2✔
2632
                return ErrPendingRemoteUpdates
×
2633
        }
×
2634
        err := l.quiescer.RecvStfu(*stfu)
2✔
2635
        if err != nil {
2✔
2636
                return err
×
2637
        }
×
2638

2639
        // If we can immediately send an Stfu response back, we will.
2640
        if l.noDanglingUpdates(lntypes.Local) {
3✔
2641
                return l.quiescer.SendOwedStfu()
1✔
2642
        }
1✔
2643

2644
        return nil
1✔
2645
}
2646

2647
// stfuFailf fails the link in the case where the requirements of the quiescence
2648
// protocol are violated. In all cases we opt to drop the connection as only
2649
// link state (as opposed to channel state) is affected.
2650
func (l *channelLink) stfuFailf(format string, args ...interface{}) {
×
2651
        l.failf(LinkFailureError{
×
2652
                code:             ErrStfuViolation,
×
2653
                FailureAction:    LinkFailureDisconnect,
×
2654
                PermanentFailure: false,
×
2655
                Warning:          true,
×
2656
        }, format, args...)
×
2657
}
×
2658

2659
// noDanglingUpdates returns true when there are 0 updates that were originally
2660
// issued by whose on either the Local or Remote commitment transaction.
2661
func (l *channelLink) noDanglingUpdates(whose lntypes.ChannelParty) bool {
1,195✔
2662
        pendingOnLocal := l.channel.NumPendingUpdates(
1,195✔
2663
                whose, lntypes.Local,
1,195✔
2664
        )
1,195✔
2665
        pendingOnRemote := l.channel.NumPendingUpdates(
1,195✔
2666
                whose, lntypes.Remote,
1,195✔
2667
        )
1,195✔
2668

1,195✔
2669
        return pendingOnLocal == 0 && pendingOnRemote == 0
1,195✔
2670
}
1,195✔
2671

2672
// ackDownStreamPackets is responsible for removing htlcs from a link's mailbox
2673
// for packets delivered from server, and cleaning up any circuits closed by
2674
// signing a previous commitment txn. This method ensures that the circuits are
2675
// removed from the circuit map before removing them from the link's mailbox,
2676
// otherwise it could be possible for some circuit to be missed if this link
2677
// flaps.
2678
func (l *channelLink) ackDownStreamPackets() error {
1,369✔
2679
        // First, remove the downstream Add packets that were included in the
1,369✔
2680
        // previous commitment signature. This will prevent the Adds from being
1,369✔
2681
        // replayed if this link disconnects.
1,369✔
2682
        for _, inKey := range l.openedCircuits {
1,833✔
2683
                // In order to test the sphinx replay logic of the remote
464✔
2684
                // party, unsafe replay does not acknowledge the packets from
464✔
2685
                // the mailbox. We can then force a replay of any Add packets
464✔
2686
                // held in memory by disconnecting and reconnecting the link.
464✔
2687
                if l.cfg.UnsafeReplay {
464✔
UNCOV
2688
                        continue
×
2689
                }
2690

2691
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
464✔
2692
                l.mailBox.AckPacket(inKey)
464✔
2693
        }
2694

2695
        // Now, we will delete all circuits closed by the previous commitment
2696
        // signature, which is the result of downstream Settle/Fail packets. We
2697
        // batch them here to ensure circuits are closed atomically and for
2698
        // performance.
2699
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
1,369✔
2700
        switch err {
1,369✔
2701
        case nil:
1,369✔
2702
                // Successful deletion.
2703

2704
        default:
×
2705
                l.log.Errorf("unable to delete %d circuits: %v",
×
2706
                        len(l.closedCircuits), err)
×
2707
                return err
×
2708
        }
2709

2710
        // With the circuits removed from memory and disk, we now ack any
2711
        // Settle/Fails in the mailbox to ensure they do not get redelivered
2712
        // after startup. If forgive is enabled and we've reached this point,
2713
        // the circuits must have been removed at some point, so it is now safe
2714
        // to un-queue the corresponding Settle/Fails.
2715
        for _, inKey := range l.closedCircuits {
1,408✔
2716
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
39✔
2717
                        inKey)
39✔
2718
                l.mailBox.AckPacket(inKey)
39✔
2719
        }
39✔
2720

2721
        // Lastly, reset our buffers to be empty while keeping any acquired
2722
        // growth in the backing array.
2723
        l.openedCircuits = l.openedCircuits[:0]
1,369✔
2724
        l.closedCircuits = l.closedCircuits[:0]
1,369✔
2725

1,369✔
2726
        return nil
1,369✔
2727
}
2728

2729
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
2730
// the link.
2731
func (l *channelLink) updateCommitTxOrFail() bool {
1,223✔
2732
        err := l.updateCommitTx()
1,223✔
2733
        switch err {
1,223✔
2734
        // No error encountered, success.
2735
        case nil:
1,213✔
2736

2737
        // A duplicate keystone error should be resolved and is not fatal, so
2738
        // we won't send an Error message to the peer.
2739
        case ErrDuplicateKeystone:
×
2740
                l.failf(LinkFailureError{code: ErrCircuitError},
×
2741
                        "temporary circuit error: %v", err)
×
2742
                return false
×
2743

2744
        // Any other error is treated results in an Error message being sent to
2745
        // the peer.
2746
        default:
10✔
2747
                l.failf(LinkFailureError{code: ErrInternalError},
10✔
2748
                        "unable to update commitment: %v", err)
10✔
2749
                return false
10✔
2750
        }
2751

2752
        return true
1,213✔
2753
}
2754

2755
// updateCommitTx signs, then sends an update to the remote peer adding a new
2756
// commitment to their commitment chain which includes all the latest updates
2757
// we've received+processed up to this point.
2758
func (l *channelLink) updateCommitTx() error {
1,281✔
2759
        // Preemptively write all pending keystones to disk, just in case the
1,281✔
2760
        // HTLCs we have in memory are included in the subsequent attempt to
1,281✔
2761
        // sign a commitment state.
1,281✔
2762
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
1,281✔
2763
        if err != nil {
1,281✔
2764
                // If ErrDuplicateKeystone is returned, the caller will catch
×
2765
                // it.
×
2766
                return err
×
2767
        }
×
2768

2769
        // Reset the batch, but keep the backing buffer to avoid reallocating.
2770
        l.keystoneBatch = l.keystoneBatch[:0]
1,281✔
2771

1,281✔
2772
        // If hodl.Commit mode is active, we will refrain from attempting to
1,281✔
2773
        // commit any in-memory modifications to the channel state. Exiting here
1,281✔
2774
        // permits testing of either the switch or link's ability to trim
1,281✔
2775
        // circuits that have been opened, but unsuccessfully committed.
1,281✔
2776
        if l.cfg.HodlMask.Active(hodl.Commit) {
1,285✔
2777
                l.log.Warnf(hodl.Commit.Warning())
4✔
2778
                return nil
4✔
2779
        }
4✔
2780

2781
        ctx, done := l.WithCtxQuitNoTimeout()
1,277✔
2782
        defer done()
1,277✔
2783

1,277✔
2784
        newCommit, err := l.channel.SignNextCommitment(ctx)
1,277✔
2785
        if err == lnwallet.ErrNoWindow {
1,355✔
2786
                l.cfg.PendingCommitTicker.Resume()
78✔
2787
                l.log.Trace("PendingCommitTicker resumed")
78✔
2788

78✔
2789
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
78✔
2790
                l.log.Tracef("revocation window exhausted, unable to send: "+
78✔
2791
                        "%v, pend_updates=%v, dangling_closes%v", n,
78✔
2792
                        lnutils.SpewLogClosure(l.openedCircuits),
78✔
2793
                        lnutils.SpewLogClosure(l.closedCircuits))
78✔
2794

78✔
2795
                return nil
78✔
2796
        } else if err != nil {
1,277✔
2797
                return err
×
2798
        }
×
2799

2800
        if err := l.ackDownStreamPackets(); err != nil {
1,199✔
2801
                return err
×
2802
        }
×
2803

2804
        l.cfg.PendingCommitTicker.Pause()
1,199✔
2805
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
1,199✔
2806

1,199✔
2807
        // The remote party now has a new pending commitment, so we'll update
1,199✔
2808
        // the contract court to be aware of this new set (the prior old remote
1,199✔
2809
        // pending).
1,199✔
2810
        newUpdate := &contractcourt.ContractUpdate{
1,199✔
2811
                HtlcKey: contractcourt.RemotePendingHtlcSet,
1,199✔
2812
                Htlcs:   newCommit.PendingHTLCs,
1,199✔
2813
        }
1,199✔
2814
        err = l.cfg.NotifyContractUpdate(newUpdate)
1,199✔
2815
        if err != nil {
1,199✔
2816
                l.log.Errorf("unable to notify contract update: %v", err)
×
2817
                return err
×
2818
        }
×
2819

2820
        select {
1,199✔
2821
        case <-l.Quit:
11✔
2822
                return ErrLinkShuttingDown
11✔
2823
        default:
1,188✔
2824
        }
2825

2826
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
1,188✔
2827
        if err != nil {
1,188✔
2828
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
2829
        }
×
2830

2831
        commitSig := &lnwire.CommitSig{
1,188✔
2832
                ChanID:        l.ChanID(),
1,188✔
2833
                CommitSig:     newCommit.CommitSig,
1,188✔
2834
                HtlcSigs:      newCommit.HtlcSigs,
1,188✔
2835
                PartialSig:    newCommit.PartialSig,
1,188✔
2836
                CustomRecords: auxBlobRecords,
1,188✔
2837
        }
1,188✔
2838
        l.cfg.Peer.SendMessage(false, commitSig)
1,188✔
2839

1,188✔
2840
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
1,188✔
2841
        // of commit hooks.
1,188✔
2842
        l.RWMutex.Lock()
1,188✔
2843
        l.outgoingCommitHooks.invoke()
1,188✔
2844
        l.RWMutex.Unlock()
1,188✔
2845

1,188✔
2846
        return nil
1,188✔
2847
}
2848

2849
// Peer returns the representation of remote peer with which we have the
2850
// channel link opened.
2851
//
2852
// NOTE: Part of the ChannelLink interface.
2853
func (l *channelLink) PeerPubKey() [33]byte {
441✔
2854
        return l.cfg.Peer.PubKey()
441✔
2855
}
441✔
2856

2857
// ChannelPoint returns the channel outpoint for the channel link.
2858
// NOTE: Part of the ChannelLink interface.
2859
func (l *channelLink) ChannelPoint() wire.OutPoint {
852✔
2860
        return l.channel.ChannelPoint()
852✔
2861
}
852✔
2862

2863
// ShortChanID returns the short channel ID for the channel link. The short
2864
// channel ID encodes the exact location in the main chain that the original
2865
// funding output can be found.
2866
//
2867
// NOTE: Part of the ChannelLink interface.
2868
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
4,247✔
2869
        l.RLock()
4,247✔
2870
        defer l.RUnlock()
4,247✔
2871

4,247✔
2872
        return l.channel.ShortChanID()
4,247✔
2873
}
4,247✔
2874

2875
// UpdateShortChanID updates the short channel ID for a link. This may be
2876
// required in the event that a link is created before the short chan ID for it
2877
// is known, or a re-org occurs, and the funding transaction changes location
2878
// within the chain.
2879
//
2880
// NOTE: Part of the ChannelLink interface.
UNCOV
2881
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
×
UNCOV
2882
        chanID := l.ChanID()
×
UNCOV
2883

×
UNCOV
2884
        // Refresh the channel state's short channel ID by loading it from disk.
×
UNCOV
2885
        // This ensures that the channel state accurately reflects the updated
×
UNCOV
2886
        // short channel ID.
×
UNCOV
2887
        err := l.channel.State().Refresh()
×
UNCOV
2888
        if err != nil {
×
2889
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
2890
                        "%v", chanID, err)
×
2891
                return hop.Source, err
×
2892
        }
×
2893

UNCOV
2894
        return hop.Source, nil
×
2895
}
2896

2897
// ChanID returns the channel ID for the channel link. The channel ID is a more
2898
// compact representation of a channel's full outpoint.
2899
//
2900
// NOTE: Part of the ChannelLink interface.
2901
func (l *channelLink) ChanID() lnwire.ChannelID {
3,927✔
2902
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
3,927✔
2903
}
3,927✔
2904

2905
// Bandwidth returns the total amount that can flow through the channel link at
2906
// this given instance. The value returned is expressed in millisatoshi and can
2907
// be used by callers when making forwarding decisions to determine if a link
2908
// can accept an HTLC.
2909
//
2910
// NOTE: Part of the ChannelLink interface.
2911
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
812✔
2912
        // Get the balance available on the channel for new HTLCs. This takes
812✔
2913
        // the channel reserve into account so HTLCs up to this value won't
812✔
2914
        // violate it.
812✔
2915
        return l.channel.AvailableBalance()
812✔
2916
}
812✔
2917

2918
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2919
// amount provided to the link. This check does not reserve a space, since
2920
// forwards or other payments may use the available slot, so it should be
2921
// considered best-effort.
UNCOV
2922
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
×
UNCOV
2923
        return l.channel.MayAddOutgoingHtlc(amt)
×
UNCOV
2924
}
×
2925

2926
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2927
// method.
2928
//
2929
// NOTE: Part of the dustHandler interface.
2930
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2931
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
2,523✔
2932

2,523✔
2933
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
2,523✔
2934
}
2,523✔
2935

2936
// getFeeRate is a wrapper method that retrieves the underlying channel's
2937
// feerate.
2938
//
2939
// NOTE: Part of the dustHandler interface.
2940
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
669✔
2941
        return l.channel.CommitFeeRate()
669✔
2942
}
669✔
2943

2944
// getDustClosure returns a closure that can be used by the switch or mailbox
2945
// to evaluate whether a given HTLC is dust.
2946
//
2947
// NOTE: Part of the dustHandler interface.
2948
func (l *channelLink) getDustClosure() dustClosure {
1,599✔
2949
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
1,599✔
2950
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
1,599✔
2951
        chanType := l.channel.State().ChanType
1,599✔
2952

1,599✔
2953
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
1,599✔
2954
}
1,599✔
2955

2956
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2957
// is used so that the Switch can have access to the commitment fee without
2958
// needing to have a *LightningChannel. This doesn't include dust.
2959
//
2960
// NOTE: Part of the dustHandler interface.
2961
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
1,889✔
2962
        if remote {
2,848✔
2963
                return l.channel.State().RemoteCommitment.CommitFee
959✔
2964
        }
959✔
2965

2966
        return l.channel.State().LocalCommitment.CommitFee
930✔
2967
}
2968

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

6✔
2983
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
6✔
2984

6✔
2985
        // Get the sum of dust for both the local and remote commitments using
6✔
2986
        // this "dry-run" fee.
6✔
2987
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
6✔
2988
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
6✔
2989

6✔
2990
        // Calculate the local and remote commitment fees using this dry-run
6✔
2991
        // fee.
6✔
2992
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
2993
        if err != nil {
6✔
2994
                return false, err
×
2995
        }
×
2996

2997
        // Finally, check whether the max fee exposure was exceeded on either
2998
        // future commitment transaction with the fee-rate.
2999
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
6✔
3000
        if totalLocalDust > l.cfg.MaxFeeExposure {
6✔
3001
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
3002
                        "local dust: %v, local fee: %v", l.ShortChanID(),
×
3003
                        totalLocalDust, localFee)
×
3004

×
3005
                return true, nil
×
3006
        }
×
3007

3008
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
6✔
3009
                remoteFee,
6✔
3010
        )
6✔
3011

6✔
3012
        if totalRemoteDust > l.cfg.MaxFeeExposure {
6✔
3013
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
3014
                        "remote dust: %v, remote fee: %v", l.ShortChanID(),
×
3015
                        totalRemoteDust, remoteFee)
×
3016

×
3017
                return true, nil
×
3018
        }
×
3019

3020
        return false, nil
6✔
3021
}
3022

3023
// isOverexposedWithHtlc calculates whether the proposed HTLC will make the
3024
// channel exceed the fee threshold. It first fetches the largest fee-rate that
3025
// may be on any unrevoked commitment transaction. Then, using this fee-rate,
3026
// determines if the to-be-added HTLC is dust. If the HTLC is dust, it adds to
3027
// the overall dust sum. If it is not dust, it contributes to weight, which
3028
// also adds to the overall dust sum by an increase in fees. If the dust sum on
3029
// either commitment exceeds the configured fee threshold, this function
3030
// returns true.
3031
func (l *channelLink) isOverexposedWithHtlc(htlc *lnwire.UpdateAddHTLC,
3032
        incoming bool) bool {
930✔
3033

930✔
3034
        dustClosure := l.getDustClosure()
930✔
3035

930✔
3036
        feeRate := l.channel.WorstCaseFeeRate()
930✔
3037

930✔
3038
        amount := htlc.Amount.ToSatoshis()
930✔
3039

930✔
3040
        // See if this HTLC is dust on both the local and remote commitments.
930✔
3041
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
930✔
3042
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
930✔
3043

930✔
3044
        // Calculate the dust sum for the local and remote commitments.
930✔
3045
        localDustSum := l.getDustSum(
930✔
3046
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
930✔
3047
        )
930✔
3048
        remoteDustSum := l.getDustSum(
930✔
3049
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
930✔
3050
        )
930✔
3051

930✔
3052
        // Grab the larger of the local and remote commitment fees w/o dust.
930✔
3053
        commitFee := l.getCommitFee(false)
930✔
3054

930✔
3055
        if l.getCommitFee(true) > commitFee {
959✔
3056
                commitFee = l.getCommitFee(true)
29✔
3057
        }
29✔
3058

3059
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
930✔
3060

930✔
3061
        localDustSum += commitFeeMSat
930✔
3062
        remoteDustSum += commitFeeMSat
930✔
3063

930✔
3064
        // Calculate the additional fee increase if this is a non-dust HTLC.
930✔
3065
        weight := lntypes.WeightUnit(input.HTLCWeight)
930✔
3066
        additional := lnwire.NewMSatFromSatoshis(
930✔
3067
                feeRate.FeeForWeight(weight),
930✔
3068
        )
930✔
3069

930✔
3070
        if isLocalDust {
1,563✔
3071
                // If this is dust, it doesn't contribute to weight but does
633✔
3072
                // contribute to the overall dust sum.
633✔
3073
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
633✔
3074
        } else {
930✔
3075
                // Account for the fee increase that comes with an increase in
297✔
3076
                // weight.
297✔
3077
                localDustSum += additional
297✔
3078
        }
297✔
3079

3080
        if localDustSum > l.cfg.MaxFeeExposure {
934✔
3081
                // The max fee exposure was exceeded.
4✔
3082
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
4✔
3083
                        "overexposed, total local dust: %v (current commit "+
4✔
3084
                        "fee: %v)", l.ShortChanID(), htlc, localDustSum)
4✔
3085

4✔
3086
                return true
4✔
3087
        }
4✔
3088

3089
        if isRemoteDust {
1,556✔
3090
                // If this is dust, it doesn't contribute to weight but does
630✔
3091
                // contribute to the overall dust sum.
630✔
3092
                remoteDustSum += lnwire.NewMSatFromSatoshis(amount)
630✔
3093
        } else {
926✔
3094
                // Account for the fee increase that comes with an increase in
296✔
3095
                // weight.
296✔
3096
                remoteDustSum += additional
296✔
3097
        }
296✔
3098

3099
        if remoteDustSum > l.cfg.MaxFeeExposure {
926✔
3100
                // The max fee exposure was exceeded.
×
3101
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
3102
                        "overexposed, total remote dust: %v (current commit "+
×
3103
                        "fee: %v)", l.ShortChanID(), htlc, remoteDustSum)
×
3104

×
3105
                return true
×
3106
        }
×
3107

3108
        return false
926✔
3109
}
3110

3111
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
3112
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
3113
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
3114
// whether to evaluate on the local or remote commit, and finally an HTLC
3115
// amount to test.
3116
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
3117
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
3118

3119
// dustHelper is used to construct the dustClosure.
3120
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
3121
        remoteDustLimit btcutil.Amount) dustClosure {
1,799✔
3122

1,799✔
3123
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
1,799✔
3124
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
11,291✔
3125

9,492✔
3126
                var dustLimit btcutil.Amount
9,492✔
3127
                if whoseCommit.IsLocal() {
14,238✔
3128
                        dustLimit = localDustLimit
4,746✔
3129
                } else {
9,492✔
3130
                        dustLimit = remoteDustLimit
4,746✔
3131
                }
4,746✔
3132

3133
                return lnwallet.HtlcIsDust(
9,492✔
3134
                        chantype, incoming, whoseCommit, feerate, amt,
9,492✔
3135
                        dustLimit,
9,492✔
3136
                )
9,492✔
3137
        }
3138

3139
        return isDust
1,799✔
3140
}
3141

3142
// zeroConfConfirmed returns whether or not the zero-conf channel has
3143
// confirmed on-chain.
3144
//
3145
// Part of the scidAliasHandler interface.
3146
func (l *channelLink) zeroConfConfirmed() bool {
3✔
3147
        return l.channel.State().ZeroConfConfirmed()
3✔
3148
}
3✔
3149

3150
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
3151
// should not be called for non-zero-conf channels.
3152
//
3153
// Part of the scidAliasHandler interface.
3154
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
3✔
3155
        return l.channel.State().ZeroConfRealScid()
3✔
3156
}
3✔
3157

3158
// isZeroConf returns whether or not the underlying channel is a zero-conf
3159
// channel.
3160
//
3161
// Part of the scidAliasHandler interface.
3162
func (l *channelLink) isZeroConf() bool {
213✔
3163
        return l.channel.State().IsZeroConf()
213✔
3164
}
213✔
3165

3166
// negotiatedAliasFeature returns whether or not the underlying channel has
3167
// negotiated the option-scid-alias feature bit. This will be true for both
3168
// option-scid-alias and zero-conf channel-types. It will also be true for
3169
// channels with the feature bit but without the above channel-types.
3170
//
3171
// Part of the scidAliasFeature interface.
3172
func (l *channelLink) negotiatedAliasFeature() bool {
374✔
3173
        return l.channel.State().NegotiatedAliasFeature()
374✔
3174
}
374✔
3175

3176
// getAliases returns the set of aliases for the underlying channel.
3177
//
3178
// Part of the scidAliasHandler interface.
3179
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
219✔
3180
        return l.cfg.GetAliases(l.ShortChanID())
219✔
3181
}
219✔
3182

3183
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
3184
//
3185
// Part of the scidAliasHandler interface.
3186
func (l *channelLink) attachFailAliasUpdate(closure func(
3187
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
214✔
3188

214✔
3189
        l.Lock()
214✔
3190
        l.cfg.FailAliasUpdate = closure
214✔
3191
        l.Unlock()
214✔
3192
}
214✔
3193

3194
// AttachMailBox updates the current mailbox used by this link, and hooks up
3195
// the mailbox's message and packet outboxes to the link's upstream and
3196
// downstream chans, respectively.
3197
func (l *channelLink) AttachMailBox(mailbox MailBox) {
213✔
3198
        l.Lock()
213✔
3199
        l.mailBox = mailbox
213✔
3200
        l.upstream = mailbox.MessageOutBox()
213✔
3201
        l.downstream = mailbox.PacketOutBox()
213✔
3202
        l.Unlock()
213✔
3203

213✔
3204
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
213✔
3205
        // never committed.
213✔
3206
        l.mailBox.SetFeeRate(l.getFeeRate())
213✔
3207

213✔
3208
        // Also set the mailbox's dust closure so that it can query whether HTLC's
213✔
3209
        // are dust given the current feerate.
213✔
3210
        l.mailBox.SetDustClosure(l.getDustClosure())
213✔
3211
}
213✔
3212

3213
// UpdateForwardingPolicy updates the forwarding policy for the target
3214
// ChannelLink. Once updated, the link will use the new forwarding policy to
3215
// govern if it an incoming HTLC should be forwarded or not. We assume that
3216
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
3217
// update all of the link's FwrdingPolicy's values.
3218
//
3219
// NOTE: Part of the ChannelLink interface.
3220
func (l *channelLink) UpdateForwardingPolicy(
3221
        newPolicy models.ForwardingPolicy) {
12✔
3222

12✔
3223
        l.Lock()
12✔
3224
        defer l.Unlock()
12✔
3225

12✔
3226
        l.cfg.FwrdingPolicy = newPolicy
12✔
3227
}
12✔
3228

3229
// CheckHtlcForward should return a nil error if the passed HTLC details
3230
// satisfy the current forwarding policy fo the target link. Otherwise,
3231
// a LinkError with a valid protocol failure message should be returned
3232
// in order to signal to the source of the HTLC, the policy consistency
3233
// issue.
3234
//
3235
// NOTE: Part of the ChannelLink interface.
3236
func (l *channelLink) CheckHtlcForward(payHash [32]byte,
3237
        incomingHtlcAmt, amtToForward lnwire.MilliSatoshi,
3238
        incomingTimeout, outgoingTimeout uint32,
3239
        inboundFee models.InboundFee,
3240
        heightNow uint32, originalScid lnwire.ShortChannelID) *LinkError {
49✔
3241

49✔
3242
        l.RLock()
49✔
3243
        policy := l.cfg.FwrdingPolicy
49✔
3244
        l.RUnlock()
49✔
3245

49✔
3246
        // Using the outgoing HTLC amount, we'll calculate the outgoing
49✔
3247
        // fee this incoming HTLC must carry in order to satisfy the constraints
49✔
3248
        // of the outgoing link.
49✔
3249
        outFee := ExpectedFee(policy, amtToForward)
49✔
3250

49✔
3251
        // Then calculate the inbound fee that we charge based on the sum of
49✔
3252
        // outgoing HTLC amount and outgoing fee.
49✔
3253
        inFee := inboundFee.CalcFee(amtToForward + outFee)
49✔
3254

49✔
3255
        // Add up both fee components. It is important to calculate both fees
49✔
3256
        // separately. An alternative way of calculating is to first determine
49✔
3257
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
49✔
3258
        // rounding may cause the result to be slightly higher than in the case
49✔
3259
        // of separately rounded fee components. This potentially causes failed
49✔
3260
        // forwards for senders and is something to be avoided.
49✔
3261
        expectedFee := inFee + int64(outFee)
49✔
3262

49✔
3263
        // If the actual fee is less than our expected fee, then we'll reject
49✔
3264
        // this HTLC as it didn't provide a sufficient amount of fees, or the
49✔
3265
        // values have been tampered with, or the send used incorrect/dated
49✔
3266
        // information to construct the forwarding information for this hop. In
49✔
3267
        // any case, we'll cancel this HTLC.
49✔
3268
        actualFee := int64(incomingHtlcAmt) - int64(amtToForward)
49✔
3269
        if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
55✔
3270
                l.log.Warnf("outgoing htlc(%x) has insufficient fee: "+
6✔
3271
                        "expected %v, got %v: incoming=%v, outgoing=%v, "+
6✔
3272
                        "inboundFee=%v",
6✔
3273
                        payHash[:], expectedFee, actualFee,
6✔
3274
                        incomingHtlcAmt, amtToForward, inboundFee,
6✔
3275
                )
6✔
3276

6✔
3277
                // As part of the returned error, we'll send our latest routing
6✔
3278
                // policy so the sending node obtains the most up to date data.
6✔
3279
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
12✔
3280
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
6✔
3281
                }
6✔
3282
                failure := l.createFailureWithUpdate(false, originalScid, cb)
6✔
3283
                return NewLinkError(failure)
6✔
3284
        }
3285

3286
        // Check whether the outgoing htlc satisfies the channel policy.
3287
        err := l.canSendHtlc(
43✔
3288
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
43✔
3289
                originalScid,
43✔
3290
        )
43✔
3291
        if err != nil {
56✔
3292
                return err
13✔
3293
        }
13✔
3294

3295
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
3296
        // the following constraint: the incoming time-lock minus our time-lock
3297
        // delta should equal the outgoing time lock. Otherwise, whether the
3298
        // sender messed up, or an intermediate node tampered with the HTLC.
3299
        timeDelta := policy.TimeLockDelta
30✔
3300
        if incomingTimeout < outgoingTimeout+timeDelta {
32✔
3301
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
2✔
3302
                        "expected at least %v block delta, got %v block delta",
2✔
3303
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
2✔
3304

2✔
3305
                // Grab the latest routing policy so the sending node is up to
2✔
3306
                // date with our current policy.
2✔
3307
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
3308
                        return lnwire.NewIncorrectCltvExpiry(
2✔
3309
                                incomingTimeout, *upd,
2✔
3310
                        )
2✔
3311
                }
2✔
3312
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3313
                return NewLinkError(failure)
2✔
3314
        }
3315

3316
        return nil
28✔
3317
}
3318

3319
// CheckHtlcTransit should return a nil error if the passed HTLC details
3320
// satisfy the current channel policy.  Otherwise, a LinkError with a
3321
// valid protocol failure message should be returned in order to signal
3322
// the violation. This call is intended to be used for locally initiated
3323
// payments for which there is no corresponding incoming htlc.
3324
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
3325
        amt lnwire.MilliSatoshi, timeout uint32,
3326
        heightNow uint32) *LinkError {
406✔
3327

406✔
3328
        l.RLock()
406✔
3329
        policy := l.cfg.FwrdingPolicy
406✔
3330
        l.RUnlock()
406✔
3331

406✔
3332
        // We pass in hop.Source here as this is only used in the Switch when
406✔
3333
        // trying to send over a local link. This causes the fallback mechanism
406✔
3334
        // to occur.
406✔
3335
        return l.canSendHtlc(
406✔
3336
                policy, payHash, amt, timeout, heightNow, hop.Source,
406✔
3337
        )
406✔
3338
}
406✔
3339

3340
// canSendHtlc checks whether the given htlc parameters satisfy
3341
// the channel's amount and time lock constraints.
3342
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
3343
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
3344
        heightNow uint32, originalScid lnwire.ShortChannelID) *LinkError {
449✔
3345

449✔
3346
        // As our first sanity check, we'll ensure that the passed HTLC isn't
449✔
3347
        // too small for the next hop. If so, then we'll cancel the HTLC
449✔
3348
        // directly.
449✔
3349
        if amt < policy.MinHTLCOut {
457✔
3350
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
8✔
3351
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
8✔
3352
                        amt)
8✔
3353

8✔
3354
                // As part of the returned error, we'll send our latest routing
8✔
3355
                // policy so the sending node obtains the most up to date data.
8✔
3356
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
16✔
3357
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
8✔
3358
                }
8✔
3359
                failure := l.createFailureWithUpdate(false, originalScid, cb)
8✔
3360
                return NewLinkError(failure)
8✔
3361
        }
3362

3363
        // Next, ensure that the passed HTLC isn't too large. If so, we'll
3364
        // cancel the HTLC directly.
3365
        if policy.MaxHTLC != 0 && amt > policy.MaxHTLC {
444✔
3366
                l.log.Warnf("outgoing htlc(%x) is too large: max_htlc=%v, "+
3✔
3367
                        "htlc_value=%v", payHash[:], policy.MaxHTLC, amt)
3✔
3368

3✔
3369
                // As part of the returned error, we'll send our latest routing
3✔
3370
                // policy so the sending node obtains the most up-to-date data.
3✔
3371
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
6✔
3372
                        return lnwire.NewTemporaryChannelFailure(upd)
3✔
3373
                }
3✔
3374
                failure := l.createFailureWithUpdate(false, originalScid, cb)
3✔
3375
                return NewDetailedLinkError(failure, OutgoingFailureHTLCExceedsMax)
3✔
3376
        }
3377

3378
        // We want to avoid offering an HTLC which will expire in the near
3379
        // future, so we'll reject an HTLC if the outgoing expiration time is
3380
        // too close to the current height.
3381
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
440✔
3382
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
2✔
3383
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
2✔
3384
                        timeout, heightNow)
2✔
3385

2✔
3386
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
3387
                        return lnwire.NewExpiryTooSoon(*upd)
2✔
3388
                }
2✔
3389
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3390
                return NewLinkError(failure)
2✔
3391
        }
3392

3393
        // Check absolute max delta.
3394
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
437✔
3395
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
1✔
3396
                        "the future: got %v, but maximum is %v", payHash[:],
1✔
3397
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
1✔
3398

1✔
3399
                return NewLinkError(&lnwire.FailExpiryTooFar{})
1✔
3400
        }
1✔
3401

3402
        // Check to see if there is enough balance in this channel.
3403
        if amt > l.Bandwidth() {
436✔
3404
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
1✔
3405
                        "larger than %v", amt, l.Bandwidth())
1✔
3406
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
2✔
3407
                        return lnwire.NewTemporaryChannelFailure(upd)
1✔
3408
                }
1✔
3409
                failure := l.createFailureWithUpdate(false, originalScid, cb)
1✔
3410
                return NewDetailedLinkError(
1✔
3411
                        failure, OutgoingFailureInsufficientBalance,
1✔
3412
                )
1✔
3413
        }
3414

3415
        return nil
434✔
3416
}
3417

3418
// Stats returns the statistics of channel link.
3419
//
3420
// NOTE: Part of the ChannelLink interface.
3421
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
4✔
3422
        snapshot := l.channel.StateSnapshot()
4✔
3423

4✔
3424
        return snapshot.ChannelCommitment.CommitHeight,
4✔
3425
                snapshot.TotalMSatSent,
4✔
3426
                snapshot.TotalMSatReceived
4✔
3427
}
4✔
3428

3429
// String returns the string representation of channel link.
3430
//
3431
// NOTE: Part of the ChannelLink interface.
3432
func (l *channelLink) String() string {
×
3433
        return l.channel.ChannelPoint().String()
×
3434
}
×
3435

3436
// handleSwitchPacket handles the switch packets. This packets which might be
3437
// forwarded to us from another channel link in case the htlc update came from
3438
// another peer or if the update was created by user
3439
//
3440
// NOTE: Part of the packetHandler interface.
3441
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
479✔
3442
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
479✔
3443
                pkt.inKey(), pkt.outKey())
479✔
3444

479✔
3445
        return l.mailBox.AddPacket(pkt)
479✔
3446
}
479✔
3447

3448
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
3449
// to us from remote peer we have a channel with.
3450
//
3451
// NOTE: Part of the ChannelLink interface.
3452
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
3,345✔
3453
        select {
3,345✔
3454
        case <-l.Quit:
×
3455
                // Return early if the link is already in the process of
×
3456
                // quitting. It doesn't make sense to hand the message to the
×
3457
                // mailbox here.
×
3458
                return
×
3459
        default:
3,345✔
3460
        }
3461

3462
        err := l.mailBox.AddMessage(message)
3,345✔
3463
        if err != nil {
3,345✔
3464
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
3465
        }
×
3466
}
3467

3468
// updateChannelFee updates the commitment fee-per-kw on this channel by
3469
// committing to an update_fee message.
3470
func (l *channelLink) updateChannelFee(feePerKw chainfee.SatPerKWeight) error {
3✔
3471
        l.log.Infof("updating commit fee to %v", feePerKw)
3✔
3472

3✔
3473
        // We skip sending the UpdateFee message if the channel is not
3✔
3474
        // currently eligible to forward messages.
3✔
3475
        if !l.eligibleToUpdate() {
3✔
3476
                l.log.Debugf("skipping fee update for inactive channel")
×
3477
                return nil
×
3478
        }
×
3479

3480
        // Check and see if our proposed fee-rate would make us exceed the fee
3481
        // threshold.
3482
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
3✔
3483
        if err != nil {
3✔
3484
                // This shouldn't typically happen. If it does, it indicates
×
3485
                // something is wrong with our channel state.
×
3486
                return err
×
3487
        }
×
3488

3489
        if thresholdExceeded {
3✔
3490
                return fmt.Errorf("link fee threshold exceeded")
×
3491
        }
×
3492

3493
        // First, we'll update the local fee on our commitment.
3494
        if err := l.channel.UpdateFee(feePerKw); err != nil {
3✔
3495
                return err
×
3496
        }
×
3497

3498
        // The fee passed the channel's validation checks, so we update the
3499
        // mailbox feerate.
3500
        l.mailBox.SetFeeRate(feePerKw)
3✔
3501

3✔
3502
        // We'll then attempt to send a new UpdateFee message, and also lock it
3✔
3503
        // in immediately by triggering a commitment update.
3✔
3504
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
3✔
3505
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
3506
                return err
×
3507
        }
×
3508
        return l.updateCommitTx()
3✔
3509
}
3510

3511
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
3512
// after receiving a revocation from the remote party, and reprocesses them in
3513
// the context of the provided forwarding package. Any settles or fails that
3514
// have already been acknowledged in the forwarding package will not be sent to
3515
// the switch.
3516
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
1,177✔
3517
        if len(fwdPkg.SettleFails) == 0 {
2,040✔
3518
                return
863✔
3519
        }
863✔
3520

3521
        l.log.Debugf("settle-fail-filter: %v", fwdPkg.SettleFailFilter)
314✔
3522

314✔
3523
        var switchPackets []*htlcPacket
314✔
3524
        for i, update := range fwdPkg.SettleFails {
628✔
3525
                destRef := fwdPkg.DestRef(uint16(i))
314✔
3526

314✔
3527
                // Skip any settles or fails that have already been
314✔
3528
                // acknowledged by the incoming link that originated the
314✔
3529
                // forwarded Add.
314✔
3530
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
314✔
3531
                        continue
×
3532
                }
3533

3534
                // TODO(roasbeef): rework log entries to a shared
3535
                // interface.
3536

3537
                switch msg := update.UpdateMsg.(type) {
314✔
3538
                // A settle for an HTLC we previously forwarded HTLC has been
3539
                // received. So we'll forward the HTLC to the switch which will
3540
                // handle propagating the settle to the prior hop.
3541
                case *lnwire.UpdateFulfillHTLC:
191✔
3542
                        // If hodl.SettleIncoming is requested, we will not
191✔
3543
                        // forward the SETTLE to the switch and will not signal
191✔
3544
                        // a free slot on the commitment transaction.
191✔
3545
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
191✔
3546
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
3547
                                continue
×
3548
                        }
3549

3550
                        settlePacket := &htlcPacket{
191✔
3551
                                outgoingChanID: l.ShortChanID(),
191✔
3552
                                outgoingHTLCID: msg.ID,
191✔
3553
                                destRef:        &destRef,
191✔
3554
                                htlc:           msg,
191✔
3555
                        }
191✔
3556

191✔
3557
                        // Add the packet to the batch to be forwarded, and
191✔
3558
                        // notify the overflow queue that a spare spot has been
191✔
3559
                        // freed up within the commitment state.
191✔
3560
                        switchPackets = append(switchPackets, settlePacket)
191✔
3561

3562
                // A failureCode message for a previously forwarded HTLC has
3563
                // been received. As a result a new slot will be freed up in
3564
                // our commitment state, so we'll forward this to the switch so
3565
                // the backwards undo can continue.
3566
                case *lnwire.UpdateFailHTLC:
123✔
3567
                        // If hodl.SettleIncoming is requested, we will not
123✔
3568
                        // forward the FAIL to the switch and will not signal a
123✔
3569
                        // free slot on the commitment transaction.
123✔
3570
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
123✔
3571
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
3572
                                continue
×
3573
                        }
3574

3575
                        // Fetch the reason the HTLC was canceled so we can
3576
                        // continue to propagate it. This failure originated
3577
                        // from another node, so the linkFailure field is not
3578
                        // set on the packet.
3579
                        failPacket := &htlcPacket{
123✔
3580
                                outgoingChanID: l.ShortChanID(),
123✔
3581
                                outgoingHTLCID: msg.ID,
123✔
3582
                                destRef:        &destRef,
123✔
3583
                                htlc:           msg,
123✔
3584
                        }
123✔
3585

123✔
3586
                        l.log.Debugf("Failed to send HTLC with ID=%d", msg.ID)
123✔
3587

123✔
3588
                        // If the failure message lacks an HMAC (but includes
123✔
3589
                        // the 4 bytes for encoding the message and padding
123✔
3590
                        // lengths, then this means that we received it as an
123✔
3591
                        // UpdateFailMalformedHTLC. As a result, we'll signal
123✔
3592
                        // that we need to convert this error within the switch
123✔
3593
                        // to an actual error, by encrypting it as if we were
123✔
3594
                        // the originating hop.
123✔
3595
                        convertedErrorSize := lnwire.FailureMessageLength + 4
123✔
3596
                        if len(msg.Reason) == convertedErrorSize {
126✔
3597
                                failPacket.convertedError = true
3✔
3598
                        }
3✔
3599

3600
                        // Add the packet to the batch to be forwarded, and
3601
                        // notify the overflow queue that a spare spot has been
3602
                        // freed up within the commitment state.
3603
                        switchPackets = append(switchPackets, failPacket)
123✔
3604
                }
3605
        }
3606

3607
        // Only spawn the task forward packets we have a non-zero number.
3608
        if len(switchPackets) > 0 {
628✔
3609
                go l.forwardBatch(false, switchPackets...)
314✔
3610
        }
314✔
3611
}
3612

3613
// processRemoteAdds serially processes each of the Add payment descriptors
3614
// which have been "locked-in" by receiving a revocation from the remote party.
3615
// The forwarding package provided instructs how to process this batch,
3616
// indicating whether this is the first time these Adds are being processed, or
3617
// whether we are reprocessing as a result of a failure or restart. Adds that
3618
// have already been acknowledged in the forwarding package will be ignored.
3619
//
3620
//nolint:funlen
3621
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
1,179✔
3622
        l.log.Tracef("processing %d remote adds for height %d",
1,179✔
3623
                len(fwdPkg.Adds), fwdPkg.Height)
1,179✔
3624

1,179✔
3625
        decodeReqs := make(
1,179✔
3626
                []hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds),
1,179✔
3627
        )
1,179✔
3628
        for _, update := range fwdPkg.Adds {
1,628✔
3629
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
898✔
3630
                        // Before adding the new htlc to the state machine,
449✔
3631
                        // parse the onion object in order to obtain the
449✔
3632
                        // routing information with DecodeHopIterator function
449✔
3633
                        // which process the Sphinx packet.
449✔
3634
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
449✔
3635

449✔
3636
                        req := hop.DecodeHopIteratorRequest{
449✔
3637
                                OnionReader:    onionReader,
449✔
3638
                                RHash:          msg.PaymentHash[:],
449✔
3639
                                IncomingCltv:   msg.Expiry,
449✔
3640
                                IncomingAmount: msg.Amount,
449✔
3641
                                BlindingPoint:  msg.BlindingPoint,
449✔
3642
                        }
449✔
3643

449✔
3644
                        decodeReqs = append(decodeReqs, req)
449✔
3645
                }
449✔
3646
        }
3647

3648
        // Atomically decode the incoming htlcs, simultaneously checking for
3649
        // replay attempts. A particular index in the returned, spare list of
3650
        // channel iterators should only be used if the failure code at the
3651
        // same index is lnwire.FailCodeNone.
3652
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
1,179✔
3653
                fwdPkg.ID(), decodeReqs,
1,179✔
3654
        )
1,179✔
3655
        if sphinxErr != nil {
1,179✔
3656
                l.failf(LinkFailureError{code: ErrInternalError},
×
3657
                        "unable to decode hop iterators: %v", sphinxErr)
×
3658
                return
×
3659
        }
×
3660

3661
        var switchPackets []*htlcPacket
1,179✔
3662

1,179✔
3663
        for i, update := range fwdPkg.Adds {
1,628✔
3664
                idx := uint16(i)
449✔
3665

449✔
3666
                //nolint:forcetypeassert
449✔
3667
                add := *update.UpdateMsg.(*lnwire.UpdateAddHTLC)
449✔
3668
                sourceRef := fwdPkg.SourceRef(idx)
449✔
3669

449✔
3670
                if fwdPkg.State == channeldb.FwdStateProcessed &&
449✔
3671
                        fwdPkg.AckFilter.Contains(idx) {
449✔
3672

×
3673
                        // If this index is already found in the ack filter,
×
3674
                        // the response to this forwarding decision has already
×
3675
                        // been committed by one of our commitment txns. ADDs
×
3676
                        // in this state are waiting for the rest of the fwding
×
3677
                        // package to get acked before being garbage collected.
×
3678
                        continue
×
3679
                }
3680

3681
                // An incoming HTLC add has been full-locked in. As a result we
3682
                // can now examine the forwarding details of the HTLC, and the
3683
                // HTLC itself to decide if: we should forward it, cancel it,
3684
                // or are able to settle it (and it adheres to our fee related
3685
                // constraints).
3686

3687
                // Before adding the new htlc to the state machine, parse the
3688
                // onion object in order to obtain the routing information with
3689
                // DecodeHopIterator function which process the Sphinx packet.
3690
                chanIterator, failureCode := decodeResps[i].Result()
449✔
3691
                if failureCode != lnwire.CodeNone {
451✔
3692
                        // If we're unable to process the onion blob then we
2✔
3693
                        // should send the malformed htlc error to payment
2✔
3694
                        // sender.
2✔
3695
                        l.sendMalformedHTLCError(
2✔
3696
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
2✔
3697
                        )
2✔
3698

2✔
3699
                        l.log.Errorf("unable to decode onion hop "+
2✔
3700
                                "iterator: %v", failureCode)
2✔
3701
                        continue
2✔
3702
                }
3703

3704
                heightNow := l.cfg.BestHeight()
447✔
3705

447✔
3706
                pld, routeRole, pldErr := chanIterator.HopPayload()
447✔
3707
                if pldErr != nil {
447✔
UNCOV
3708
                        // If we're unable to process the onion payload, or we
×
UNCOV
3709
                        // received invalid onion payload failure, then we
×
UNCOV
3710
                        // should send an error back to the caller so the HTLC
×
UNCOV
3711
                        // can be canceled.
×
UNCOV
3712
                        var failedType uint64
×
UNCOV
3713

×
UNCOV
3714
                        // We need to get the underlying error value, so we
×
UNCOV
3715
                        // can't use errors.As as suggested by the linter.
×
UNCOV
3716
                        //nolint:errorlint
×
UNCOV
3717
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
×
3718
                                failedType = uint64(e.Type)
×
3719
                        }
×
3720

3721
                        // If we couldn't parse the payload, make our best
3722
                        // effort at creating an error encrypter that knows
3723
                        // what blinding type we were, but if we couldn't
3724
                        // parse the payload we have no way of knowing whether
3725
                        // we were the introduction node or not.
3726
                        //
3727
                        //nolint:lll
UNCOV
3728
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
×
UNCOV
3729
                                l.cfg.ExtractErrorEncrypter,
×
UNCOV
3730
                                // We need our route role here because we
×
UNCOV
3731
                                // couldn't parse or validate the payload.
×
UNCOV
3732
                                routeRole == hop.RouteRoleIntroduction,
×
UNCOV
3733
                        )
×
UNCOV
3734
                        if failCode != lnwire.CodeNone {
×
3735
                                l.log.Errorf("could not extract error "+
×
3736
                                        "encrypter: %v", pldErr)
×
3737

×
3738
                                // We can't process this htlc, send back
×
3739
                                // malformed.
×
3740
                                l.sendMalformedHTLCError(
×
3741
                                        add.ID, failureCode, add.OnionBlob,
×
3742
                                        &sourceRef,
×
3743
                                )
×
3744

×
3745
                                continue
×
3746
                        }
3747

3748
                        // TODO: currently none of the test unit infrastructure
3749
                        // is setup to handle TLV payloads, so testing this
3750
                        // would require implementing a separate mock iterator
3751
                        // for TLV payloads that also supports injecting invalid
3752
                        // payloads. Deferring this non-trival effort till a
3753
                        // later date
UNCOV
3754
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
×
UNCOV
3755

×
UNCOV
3756
                        l.sendHTLCError(
×
UNCOV
3757
                                add, sourceRef, NewLinkError(failure),
×
UNCOV
3758
                                obfuscator, false,
×
UNCOV
3759
                        )
×
UNCOV
3760

×
UNCOV
3761
                        l.log.Errorf("unable to decode forwarding "+
×
UNCOV
3762
                                "instructions: %v", pldErr)
×
UNCOV
3763

×
UNCOV
3764
                        continue
×
3765
                }
3766

3767
                // Retrieve onion obfuscator from onion blob in order to
3768
                // produce initial obfuscation of the onion failureCode.
3769
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
447✔
3770
                        l.cfg.ExtractErrorEncrypter,
447✔
3771
                        routeRole == hop.RouteRoleIntroduction,
447✔
3772
                )
447✔
3773
                if failureCode != lnwire.CodeNone {
448✔
3774
                        // If we're unable to process the onion blob than we
1✔
3775
                        // should send the malformed htlc error to payment
1✔
3776
                        // sender.
1✔
3777
                        l.sendMalformedHTLCError(
1✔
3778
                                add.ID, failureCode, add.OnionBlob,
1✔
3779
                                &sourceRef,
1✔
3780
                        )
1✔
3781

1✔
3782
                        l.log.Errorf("unable to decode onion "+
1✔
3783
                                "obfuscator: %v", failureCode)
1✔
3784

1✔
3785
                        continue
1✔
3786
                }
3787

3788
                fwdInfo := pld.ForwardingInfo()
446✔
3789

446✔
3790
                // Check whether the payload we've just processed uses our
446✔
3791
                // node as the introduction point (gave us a blinding key in
446✔
3792
                // the payload itself) and fail it back if we don't support
446✔
3793
                // route blinding.
446✔
3794
                if fwdInfo.NextBlinding.IsSome() &&
446✔
3795
                        l.cfg.DisallowRouteBlinding {
446✔
UNCOV
3796

×
UNCOV
3797
                        failure := lnwire.NewInvalidBlinding(
×
UNCOV
3798
                                fn.Some(add.OnionBlob),
×
UNCOV
3799
                        )
×
UNCOV
3800

×
UNCOV
3801
                        l.sendHTLCError(
×
UNCOV
3802
                                add, sourceRef, NewLinkError(failure),
×
UNCOV
3803
                                obfuscator, false,
×
UNCOV
3804
                        )
×
UNCOV
3805

×
UNCOV
3806
                        l.log.Error("rejected htlc that uses use as an " +
×
UNCOV
3807
                                "introduction point when we do not support " +
×
UNCOV
3808
                                "route blinding")
×
UNCOV
3809

×
UNCOV
3810
                        continue
×
3811
                }
3812

3813
                switch fwdInfo.NextHop {
446✔
3814
                case hop.Exit:
410✔
3815
                        err := l.processExitHop(
410✔
3816
                                add, sourceRef, obfuscator, fwdInfo,
410✔
3817
                                heightNow, pld,
410✔
3818
                        )
410✔
3819
                        if err != nil {
410✔
UNCOV
3820
                                l.failf(LinkFailureError{
×
UNCOV
3821
                                        code: ErrInternalError,
×
UNCOV
3822
                                }, err.Error()) //nolint
×
UNCOV
3823

×
UNCOV
3824
                                return
×
UNCOV
3825
                        }
×
3826

3827
                // There are additional channels left within this route. So
3828
                // we'll simply do some forwarding package book-keeping.
3829
                default:
36✔
3830
                        // If hodl.AddIncoming is requested, we will not
36✔
3831
                        // validate the forwarded ADD, nor will we send the
36✔
3832
                        // packet to the htlc switch.
36✔
3833
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
36✔
3834
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3835
                                continue
×
3836
                        }
3837

3838
                        endorseValue := l.experimentalEndorsement(
36✔
3839
                                record.CustomSet(add.CustomRecords),
36✔
3840
                        )
36✔
3841
                        endorseType := uint64(
36✔
3842
                                lnwire.ExperimentalEndorsementType,
36✔
3843
                        )
36✔
3844

36✔
3845
                        switch fwdPkg.State {
36✔
UNCOV
3846
                        case channeldb.FwdStateProcessed:
×
UNCOV
3847
                                // This add was not forwarded on the previous
×
UNCOV
3848
                                // processing phase, run it through our
×
UNCOV
3849
                                // validation pipeline to reproduce an error.
×
UNCOV
3850
                                // This may trigger a different error due to
×
UNCOV
3851
                                // expiring timelocks, but we expect that an
×
UNCOV
3852
                                // error will be reproduced.
×
UNCOV
3853
                                if !fwdPkg.FwdFilter.Contains(idx) {
×
3854
                                        break
×
3855
                                }
3856

3857
                                // Otherwise, it was already processed, we can
3858
                                // can collect it and continue.
UNCOV
3859
                                outgoingAdd := &lnwire.UpdateAddHTLC{
×
UNCOV
3860
                                        Expiry:        fwdInfo.OutgoingCTLV,
×
UNCOV
3861
                                        Amount:        fwdInfo.AmountToForward,
×
UNCOV
3862
                                        PaymentHash:   add.PaymentHash,
×
UNCOV
3863
                                        BlindingPoint: fwdInfo.NextBlinding,
×
UNCOV
3864
                                }
×
UNCOV
3865

×
UNCOV
3866
                                endorseValue.WhenSome(func(e byte) {
×
UNCOV
3867
                                        custRecords := map[uint64][]byte{
×
UNCOV
3868
                                                endorseType: {e},
×
UNCOV
3869
                                        }
×
UNCOV
3870

×
UNCOV
3871
                                        outgoingAdd.CustomRecords = custRecords
×
UNCOV
3872
                                })
×
3873

3874
                                // Finally, we'll encode the onion packet for
3875
                                // the _next_ hop using the hop iterator
3876
                                // decoded for the current hop.
UNCOV
3877
                                buf := bytes.NewBuffer(
×
UNCOV
3878
                                        outgoingAdd.OnionBlob[0:0],
×
UNCOV
3879
                                )
×
UNCOV
3880

×
UNCOV
3881
                                // We know this cannot fail, as this ADD
×
UNCOV
3882
                                // was marked forwarded in a previous
×
UNCOV
3883
                                // round of processing.
×
UNCOV
3884
                                chanIterator.EncodeNextHop(buf)
×
UNCOV
3885

×
UNCOV
3886
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
×
UNCOV
3887

×
UNCOV
3888
                                //nolint:lll
×
UNCOV
3889
                                updatePacket := &htlcPacket{
×
UNCOV
3890
                                        incomingChanID:       l.ShortChanID(),
×
UNCOV
3891
                                        incomingHTLCID:       add.ID,
×
UNCOV
3892
                                        outgoingChanID:       fwdInfo.NextHop,
×
UNCOV
3893
                                        sourceRef:            &sourceRef,
×
UNCOV
3894
                                        incomingAmount:       add.Amount,
×
UNCOV
3895
                                        amount:               outgoingAdd.Amount,
×
UNCOV
3896
                                        htlc:                 outgoingAdd,
×
UNCOV
3897
                                        obfuscator:           obfuscator,
×
UNCOV
3898
                                        incomingTimeout:      add.Expiry,
×
UNCOV
3899
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
×
UNCOV
3900
                                        inOnionCustomRecords: pld.CustomRecords(),
×
UNCOV
3901
                                        inboundFee:           inboundFee,
×
UNCOV
3902
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
×
UNCOV
3903
                                }
×
UNCOV
3904
                                switchPackets = append(
×
UNCOV
3905
                                        switchPackets, updatePacket,
×
UNCOV
3906
                                )
×
UNCOV
3907

×
UNCOV
3908
                                continue
×
3909
                        }
3910

3911
                        // TODO(roasbeef): ensure don't accept outrageous
3912
                        // timeout for htlc
3913

3914
                        // With all our forwarding constraints met, we'll
3915
                        // create the outgoing HTLC using the parameters as
3916
                        // specified in the forwarding info.
3917
                        addMsg := &lnwire.UpdateAddHTLC{
36✔
3918
                                Expiry:        fwdInfo.OutgoingCTLV,
36✔
3919
                                Amount:        fwdInfo.AmountToForward,
36✔
3920
                                PaymentHash:   add.PaymentHash,
36✔
3921
                                BlindingPoint: fwdInfo.NextBlinding,
36✔
3922
                        }
36✔
3923

36✔
3924
                        endorseValue.WhenSome(func(e byte) {
72✔
3925
                                addMsg.CustomRecords = map[uint64][]byte{
36✔
3926
                                        endorseType: {e},
36✔
3927
                                }
36✔
3928
                        })
36✔
3929

3930
                        // Finally, we'll encode the onion packet for the
3931
                        // _next_ hop using the hop iterator decoded for the
3932
                        // current hop.
3933
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
36✔
3934
                        err := chanIterator.EncodeNextHop(buf)
36✔
3935
                        if err != nil {
36✔
3936
                                l.log.Errorf("unable to encode the "+
×
3937
                                        "remaining route %v", err)
×
3938

×
3939
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:lll
×
3940
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
3941
                                }
×
3942

3943
                                failure := l.createFailureWithUpdate(
×
3944
                                        true, hop.Source, cb,
×
3945
                                )
×
3946

×
3947
                                l.sendHTLCError(
×
3948
                                        add, sourceRef, NewLinkError(failure),
×
3949
                                        obfuscator, false,
×
3950
                                )
×
3951
                                continue
×
3952
                        }
3953

3954
                        // Now that this add has been reprocessed, only append
3955
                        // it to our list of packets to forward to the switch
3956
                        // this is the first time processing the add. If the
3957
                        // fwd pkg has already been processed, then we entered
3958
                        // the above section to recreate a previous error.  If
3959
                        // the packet had previously been forwarded, it would
3960
                        // have been added to switchPackets at the top of this
3961
                        // section.
3962
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
72✔
3963
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
36✔
3964

36✔
3965
                                //nolint:lll
36✔
3966
                                updatePacket := &htlcPacket{
36✔
3967
                                        incomingChanID:       l.ShortChanID(),
36✔
3968
                                        incomingHTLCID:       add.ID,
36✔
3969
                                        outgoingChanID:       fwdInfo.NextHop,
36✔
3970
                                        sourceRef:            &sourceRef,
36✔
3971
                                        incomingAmount:       add.Amount,
36✔
3972
                                        amount:               addMsg.Amount,
36✔
3973
                                        htlc:                 addMsg,
36✔
3974
                                        obfuscator:           obfuscator,
36✔
3975
                                        incomingTimeout:      add.Expiry,
36✔
3976
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
36✔
3977
                                        inOnionCustomRecords: pld.CustomRecords(),
36✔
3978
                                        inboundFee:           inboundFee,
36✔
3979
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
36✔
3980
                                }
36✔
3981

36✔
3982
                                fwdPkg.FwdFilter.Set(idx)
36✔
3983
                                switchPackets = append(switchPackets,
36✔
3984
                                        updatePacket)
36✔
3985
                        }
36✔
3986
                }
3987
        }
3988

3989
        // Commit the htlcs we are intending to forward if this package has not
3990
        // been fully processed.
3991
        if fwdPkg.State == channeldb.FwdStateLockedIn {
2,355✔
3992
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
1,176✔
3993
                if err != nil {
1,176✔
3994
                        l.failf(LinkFailureError{code: ErrInternalError},
×
3995
                                "unable to set fwd filter: %v", err)
×
3996
                        return
×
3997
                }
×
3998
        }
3999

4000
        if len(switchPackets) == 0 {
2,322✔
4001
                return
1,143✔
4002
        }
1,143✔
4003

4004
        replay := fwdPkg.State != channeldb.FwdStateLockedIn
36✔
4005

36✔
4006
        l.log.Debugf("forwarding %d packets to switch: replay=%v",
36✔
4007
                len(switchPackets), replay)
36✔
4008

36✔
4009
        // NOTE: This call is made synchronous so that we ensure all circuits
36✔
4010
        // are committed in the exact order that they are processed in the link.
36✔
4011
        // Failing to do this could cause reorderings/gaps in the range of
36✔
4012
        // opened circuits, which violates assumptions made by the circuit
36✔
4013
        // trimming.
36✔
4014
        l.forwardBatch(replay, switchPackets...)
36✔
4015
}
4016

4017
// experimentalEndorsement returns the value to set for our outgoing
4018
// experimental endorsement field, and a boolean indicating whether it should
4019
// be populated on the outgoing htlc.
4020
func (l *channelLink) experimentalEndorsement(
4021
        customUpdateAdd record.CustomSet) fn.Option[byte] {
36✔
4022

36✔
4023
        // Only relay experimental signal if we are within the experiment
36✔
4024
        // period.
36✔
4025
        if !l.cfg.ShouldFwdExpEndorsement() {
36✔
UNCOV
4026
                return fn.None[byte]()
×
UNCOV
4027
        }
×
4028

4029
        // If we don't have any custom records or the experimental field is
4030
        // not set, just forward a zero value.
4031
        if len(customUpdateAdd) == 0 {
72✔
4032
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
36✔
4033
        }
36✔
4034

UNCOV
4035
        t := uint64(lnwire.ExperimentalEndorsementType)
×
UNCOV
4036
        value, set := customUpdateAdd[t]
×
UNCOV
4037
        if !set {
×
4038
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4039
        }
×
4040

4041
        // We expect at least one byte for this field, consider it invalid if
4042
        // it has no data and just forward a zero value.
UNCOV
4043
        if len(value) == 0 {
×
4044
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4045
        }
×
4046

4047
        // Only forward endorsed if the incoming link is endorsed.
UNCOV
4048
        if value[0] == lnwire.ExperimentalEndorsed {
×
UNCOV
4049
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
×
UNCOV
4050
        }
×
4051

4052
        // Forward as unendorsed otherwise, including cases where we've
4053
        // received an invalid value that uses more than 3 bits of information.
UNCOV
4054
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4055
}
4056

4057
// processExitHop handles an htlc for which this link is the exit hop. It
4058
// returns a boolean indicating whether the commitment tx needs an update.
4059
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
4060
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
4061
        fwdInfo hop.ForwardingInfo, heightNow uint32,
4062
        payload invoices.Payload) error {
410✔
4063

410✔
4064
        // If hodl.ExitSettle is requested, we will not validate the final hop's
410✔
4065
        // ADD, nor will we settle the corresponding invoice or respond with the
410✔
4066
        // preimage.
410✔
4067
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
517✔
4068
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
107✔
4069
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
107✔
4070

107✔
4071
                return nil
107✔
4072
        }
107✔
4073

4074
        // As we're the exit hop, we'll double check the hop-payload included in
4075
        // the HTLC to ensure that it was crafted correctly by the sender and
4076
        // is compatible with the HTLC we were extended.
4077
        //
4078
        // For a special case, if the fwdInfo doesn't have any blinded path
4079
        // information, and the incoming HTLC had special extra data, then
4080
        // we'll skip this amount check. The invoice acceptor will make sure we
4081
        // reject the HTLC if it's not containing the correct amount after
4082
        // examining the custom data.
4083
        hasBlindedPath := fwdInfo.NextBlinding.IsSome()
303✔
4084
        customHTLC := len(add.CustomRecords) > 0 && !hasBlindedPath
303✔
4085
        log.Tracef("Exit hop has_blinded_path=%v custom_htlc_bypass=%v",
303✔
4086
                hasBlindedPath, customHTLC)
303✔
4087

303✔
4088
        if !customHTLC && add.Amount < fwdInfo.AmountToForward {
403✔
4089
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
100✔
4090
                        "incompatible value: expected <=%v, got %v",
100✔
4091
                        add.PaymentHash, add.Amount, fwdInfo.AmountToForward)
100✔
4092

100✔
4093
                failure := NewLinkError(
100✔
4094
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
100✔
4095
                )
100✔
4096
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
100✔
4097

100✔
4098
                return nil
100✔
4099
        }
100✔
4100

4101
        // We'll also ensure that our time-lock value has been computed
4102
        // correctly.
4103
        if add.Expiry < fwdInfo.OutgoingCTLV {
204✔
4104
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
1✔
4105
                        "incompatible time-lock: expected <=%v, got %v",
1✔
4106
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
1✔
4107

1✔
4108
                failure := NewLinkError(
1✔
4109
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
1✔
4110
                )
1✔
4111

1✔
4112
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
1✔
4113

1✔
4114
                return nil
1✔
4115
        }
1✔
4116

4117
        // Notify the invoiceRegistry of the exit hop htlc. If we crash right
4118
        // after this, this code will be re-executed after restart. We will
4119
        // receive back a resolution event.
4120
        invoiceHash := lntypes.Hash(add.PaymentHash)
202✔
4121

202✔
4122
        circuitKey := models.CircuitKey{
202✔
4123
                ChanID: l.ShortChanID(),
202✔
4124
                HtlcID: add.ID,
202✔
4125
        }
202✔
4126

202✔
4127
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
202✔
4128
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
202✔
4129
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
202✔
4130
        )
202✔
4131
        if err != nil {
202✔
UNCOV
4132
                return err
×
UNCOV
4133
        }
×
4134

4135
        // Create a hodlHtlc struct and decide either resolved now or later.
4136
        htlc := hodlHtlc{
202✔
4137
                add:        add,
202✔
4138
                sourceRef:  sourceRef,
202✔
4139
                obfuscator: obfuscator,
202✔
4140
        }
202✔
4141

202✔
4142
        // If the event is nil, the invoice is being held, so we save payment
202✔
4143
        // descriptor for future reference.
202✔
4144
        if event == nil {
258✔
4145
                l.hodlMap[circuitKey] = htlc
56✔
4146
                return nil
56✔
4147
        }
56✔
4148

4149
        // Process the received resolution.
4150
        return l.processHtlcResolution(event, htlc)
146✔
4151
}
4152

4153
// settleHTLC settles the HTLC on the channel.
4154
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
4155
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
197✔
4156

197✔
4157
        hash := preimage.Hash()
197✔
4158

197✔
4159
        l.log.Infof("settling htlc %v as exit hop", hash)
197✔
4160

197✔
4161
        err := l.channel.SettleHTLC(
197✔
4162
                preimage, htlcIndex, &sourceRef, nil, nil,
197✔
4163
        )
197✔
4164
        if err != nil {
197✔
4165
                return fmt.Errorf("unable to settle htlc: %w", err)
×
4166
        }
×
4167

4168
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
4169
        // fake one before sending it to the peer.
4170
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
197✔
UNCOV
4171
                l.log.Warnf(hodl.BogusSettle.Warning())
×
UNCOV
4172
                preimage = [32]byte{}
×
UNCOV
4173
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
×
UNCOV
4174
        }
×
4175

4176
        // HTLC was successfully settled locally send notification about it
4177
        // remote peer.
4178
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
197✔
4179
                ChanID:          l.ChanID(),
197✔
4180
                ID:              htlcIndex,
197✔
4181
                PaymentPreimage: preimage,
197✔
4182
        })
197✔
4183

197✔
4184
        // Once we have successfully settled the htlc, notify a settle event.
197✔
4185
        l.cfg.HtlcNotifier.NotifySettleEvent(
197✔
4186
                HtlcKey{
197✔
4187
                        IncomingCircuit: models.CircuitKey{
197✔
4188
                                ChanID: l.ShortChanID(),
197✔
4189
                                HtlcID: htlcIndex,
197✔
4190
                        },
197✔
4191
                },
197✔
4192
                preimage,
197✔
4193
                HtlcEventTypeReceive,
197✔
4194
        )
197✔
4195

197✔
4196
        return nil
197✔
4197
}
4198

4199
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
4200
// err chan for the individual responses. This method is intended to be spawned
4201
// as a goroutine so the responses can be handled in the background.
4202
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
575✔
4203
        // Don't forward packets for which we already have a response in our
575✔
4204
        // mailbox. This could happen if a packet fails and is buffered in the
575✔
4205
        // mailbox, and the incoming link flaps.
575✔
4206
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
575✔
4207
        for _, pkt := range packets {
1,150✔
4208
                if l.mailBox.HasPacket(pkt.inKey()) {
575✔
UNCOV
4209
                        continue
×
4210
                }
4211

4212
                filteredPkts = append(filteredPkts, pkt)
575✔
4213
        }
4214

4215
        err := l.cfg.ForwardPackets(l.Quit, replay, filteredPkts...)
575✔
4216
        if err != nil {
586✔
4217
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
4218
                        "settle/fail over htlcswitch: %v", err)
11✔
4219
        }
11✔
4220
}
4221

4222
// sendHTLCError functions cancels HTLC and send cancel message back to the
4223
// peer from which HTLC was received.
4224
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
4225
        sourceRef channeldb.AddRef, failure *LinkError,
4226
        e hop.ErrorEncrypter, isReceive bool) {
105✔
4227

105✔
4228
        reason, err := e.EncryptFirstHop(failure.WireMessage())
105✔
4229
        if err != nil {
105✔
4230
                l.log.Errorf("unable to obfuscate error: %v", err)
×
4231
                return
×
4232
        }
×
4233

4234
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
105✔
4235
        if err != nil {
105✔
4236
                l.log.Errorf("unable cancel htlc: %v", err)
×
4237
                return
×
4238
        }
×
4239

4240
        // Send the appropriate failure message depending on whether we're
4241
        // in a blinded route or not.
4242
        if err := l.sendIncomingHTLCFailureMsg(
105✔
4243
                add.ID, e, reason,
105✔
4244
        ); err != nil {
105✔
4245
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
4246
                return
×
4247
        }
×
4248

4249
        // Notify a link failure on our incoming link. Outgoing htlc information
4250
        // is not available at this point, because we have not decrypted the
4251
        // onion, so it is excluded.
4252
        var eventType HtlcEventType
105✔
4253
        if isReceive {
210✔
4254
                eventType = HtlcEventTypeReceive
105✔
4255
        } else {
105✔
UNCOV
4256
                eventType = HtlcEventTypeForward
×
UNCOV
4257
        }
×
4258

4259
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
105✔
4260
                HtlcKey{
105✔
4261
                        IncomingCircuit: models.CircuitKey{
105✔
4262
                                ChanID: l.ShortChanID(),
105✔
4263
                                HtlcID: add.ID,
105✔
4264
                        },
105✔
4265
                },
105✔
4266
                HtlcInfo{
105✔
4267
                        IncomingTimeLock: add.Expiry,
105✔
4268
                        IncomingAmt:      add.Amount,
105✔
4269
                },
105✔
4270
                eventType,
105✔
4271
                failure,
105✔
4272
                true,
105✔
4273
        )
105✔
4274
}
4275

4276
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
4277
// peer from which the HTLC was received. This function is primarily used to
4278
// handle the special requirements of route blinding, specifically:
4279
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
4280
// - Introduction nodes should return regular HTLC failure messages.
4281
//
4282
// It accepts the original opaque failure, which will be used in the case
4283
// that we're not part of a blinded route and an error encrypter that'll be
4284
// used if we are the introduction node and need to present an error as if
4285
// we're the failing party.
4286
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
4287
        e hop.ErrorEncrypter,
4288
        originalFailure lnwire.OpaqueReason) error {
121✔
4289

121✔
4290
        var msg lnwire.Message
121✔
4291
        switch {
121✔
4292
        // Our circuit's error encrypter will be nil if this was a locally
4293
        // initiated payment. We can only hit a blinded error for a locally
4294
        // initiated payment if we allow ourselves to be picked as the
4295
        // introduction node for our own payments and in that case we
4296
        // shouldn't reach this code. To prevent the HTLC getting stuck,
4297
        // we fail it back and log an error.
4298
        // code.
4299
        case e == nil:
×
4300
                msg = &lnwire.UpdateFailHTLC{
×
4301
                        ChanID: l.ChanID(),
×
4302
                        ID:     htlcIndex,
×
4303
                        Reason: originalFailure,
×
4304
                }
×
4305

×
4306
                l.log.Errorf("Unexpected blinded failure when "+
×
4307
                        "we are the sending node, incoming htlc: %v(%v)",
×
4308
                        l.ShortChanID(), htlcIndex)
×
4309

4310
        // For cleartext hops (ie, non-blinded/normal) we don't need any
4311
        // transformation on the error message and can just send the original.
4312
        case !e.Type().IsBlinded():
121✔
4313
                msg = &lnwire.UpdateFailHTLC{
121✔
4314
                        ChanID: l.ChanID(),
121✔
4315
                        ID:     htlcIndex,
121✔
4316
                        Reason: originalFailure,
121✔
4317
                }
121✔
4318

4319
        // When we're the introduction node, we need to convert the error to
4320
        // a UpdateFailHTLC.
UNCOV
4321
        case e.Type() == hop.EncrypterTypeIntroduction:
×
UNCOV
4322
                l.log.Debugf("Introduction blinded node switching out failure "+
×
UNCOV
4323
                        "error: %v", htlcIndex)
×
UNCOV
4324

×
UNCOV
4325
                // The specification does not require that we set the onion
×
UNCOV
4326
                // blob.
×
UNCOV
4327
                failureMsg := lnwire.NewInvalidBlinding(
×
UNCOV
4328
                        fn.None[[lnwire.OnionPacketSize]byte](),
×
UNCOV
4329
                )
×
UNCOV
4330
                reason, err := e.EncryptFirstHop(failureMsg)
×
UNCOV
4331
                if err != nil {
×
4332
                        return err
×
4333
                }
×
4334

UNCOV
4335
                msg = &lnwire.UpdateFailHTLC{
×
UNCOV
4336
                        ChanID: l.ChanID(),
×
UNCOV
4337
                        ID:     htlcIndex,
×
UNCOV
4338
                        Reason: reason,
×
UNCOV
4339
                }
×
4340

4341
        // If we are a relaying node, we need to switch out any error that
4342
        // we've received to a malformed HTLC error.
UNCOV
4343
        case e.Type() == hop.EncrypterTypeRelaying:
×
UNCOV
4344
                l.log.Debugf("Relaying blinded node switching out malformed "+
×
UNCOV
4345
                        "error: %v", htlcIndex)
×
UNCOV
4346

×
UNCOV
4347
                msg = &lnwire.UpdateFailMalformedHTLC{
×
UNCOV
4348
                        ChanID:      l.ChanID(),
×
UNCOV
4349
                        ID:          htlcIndex,
×
UNCOV
4350
                        FailureCode: lnwire.CodeInvalidBlinding,
×
UNCOV
4351
                }
×
4352

4353
        default:
×
4354
                return fmt.Errorf("unexpected encrypter: %d", e)
×
4355
        }
4356

4357
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
121✔
4358
                l.log.Warnf("Send update fail failed: %v", err)
×
4359
        }
×
4360

4361
        return nil
121✔
4362
}
4363

4364
// sendMalformedHTLCError helper function which sends the malformed HTLC update
4365
// to the payment sender.
4366
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
4367
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
4368
        sourceRef *channeldb.AddRef) {
3✔
4369

3✔
4370
        shaOnionBlob := sha256.Sum256(onionBlob[:])
3✔
4371
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
3✔
4372
        if err != nil {
3✔
4373
                l.log.Errorf("unable cancel htlc: %v", err)
×
4374
                return
×
4375
        }
×
4376

4377
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
3✔
4378
                ChanID:       l.ChanID(),
3✔
4379
                ID:           htlcIndex,
3✔
4380
                ShaOnionBlob: shaOnionBlob,
3✔
4381
                FailureCode:  code,
3✔
4382
        })
3✔
4383
}
4384

4385
// failf is a function which is used to encapsulate the action necessary for
4386
// properly failing the link. It takes a LinkFailureError, which will be passed
4387
// to the OnChannelFailure closure, in order for it to determine if we should
4388
// force close the channel, and if we should send an error message to the
4389
// remote peer.
4390
func (l *channelLink) failf(linkErr LinkFailureError, format string,
4391
        a ...interface{}) {
14✔
4392

14✔
4393
        reason := fmt.Errorf(format, a...)
14✔
4394

14✔
4395
        // Return if we have already notified about a failure.
14✔
4396
        if l.failed {
14✔
UNCOV
4397
                l.log.Warnf("ignoring link failure (%v), as link already "+
×
UNCOV
4398
                        "failed", reason)
×
UNCOV
4399
                return
×
UNCOV
4400
        }
×
4401

4402
        l.log.Errorf("failing link: %s with error: %v", reason, linkErr)
14✔
4403

14✔
4404
        // Set failed, such that we won't process any more updates, and notify
14✔
4405
        // the peer about the failure.
14✔
4406
        l.failed = true
14✔
4407
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
14✔
4408
}
4409

4410
// FundingCustomBlob returns the custom funding blob of the channel that this
4411
// link is associated with. The funding blob represents static information about
4412
// the channel that was created at channel funding time.
4413
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
4414
        if l.channel == nil {
×
4415
                return fn.None[tlv.Blob]()
×
4416
        }
×
4417

4418
        if l.channel.State() == nil {
×
4419
                return fn.None[tlv.Blob]()
×
4420
        }
×
4421

4422
        return l.channel.State().CustomBlob
×
4423
}
4424

4425
// CommitmentCustomBlob returns the custom blob of the current local commitment
4426
// of the channel that this link is associated with.
4427
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
4428
        if l.channel == nil {
×
4429
                return fn.None[tlv.Blob]()
×
4430
        }
×
4431

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