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

lightningnetwork / lnd / 10207481183

01 Aug 2024 11:52PM UTC coverage: 58.679% (+0.09%) from 58.591%
10207481183

push

github

web-flow
Merge pull request #8836 from hieblmi/payment-failure-reason-cancel

routing: add payment failure reason `FailureReasonCancel`

7 of 30 new or added lines in 5 files covered. (23.33%)

1662 existing lines in 21 files now uncovered.

125454 of 213798 relevant lines covered (58.68%)

28679.1 hits per line

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

80.59
/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"
17
        "github.com/lightningnetwork/lnd/build"
18
        "github.com/lightningnetwork/lnd/channeldb"
19
        "github.com/lightningnetwork/lnd/channeldb/models"
20
        "github.com/lightningnetwork/lnd/contractcourt"
21
        "github.com/lightningnetwork/lnd/fn"
22
        "github.com/lightningnetwork/lnd/htlcswitch/hodl"
23
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
24
        "github.com/lightningnetwork/lnd/input"
25
        "github.com/lightningnetwork/lnd/invoices"
26
        "github.com/lightningnetwork/lnd/lnpeer"
27
        "github.com/lightningnetwork/lnd/lntypes"
28
        "github.com/lightningnetwork/lnd/lnutils"
29
        "github.com/lightningnetwork/lnd/lnwallet"
30
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
31
        "github.com/lightningnetwork/lnd/lnwire"
32
        "github.com/lightningnetwork/lnd/queue"
33
        "github.com/lightningnetwork/lnd/ticker"
34
)
35

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

283
        // MaxFeeExposure is the threshold in milli-satoshis after which we'll
284
        // restrict the flow of HTLCs and fee updates.
285
        MaxFeeExposure lnwire.MilliSatoshi
286
}
287

288
// channelLink is the service which drives a channel's commitment update
289
// state-machine. In the event that an HTLC needs to be propagated to another
290
// link, the forward handler from config is used which sends HTLC to the
291
// switch. Additionally, the link encapsulate logic of commitment protocol
292
// message ordering and updates.
293
type channelLink struct {
294
        // The following fields are only meant to be used *atomically*
295
        started       int32
296
        reestablished int32
297
        shutdown      int32
298

299
        // failed should be set to true in case a link error happens, making
300
        // sure we don't process any more updates.
301
        failed bool
302

303
        // keystoneBatch represents a volatile list of keystones that must be
304
        // written before attempting to sign the next commitment txn. These
305
        // represent all the HTLC's forwarded to the link from the switch. Once
306
        // we lock them into our outgoing commitment, then the circuit has a
307
        // keystone, and is fully opened.
308
        keystoneBatch []Keystone
309

310
        // openedCircuits is the set of all payment circuits that will be open
311
        // once we make our next commitment. After making the commitment we'll
312
        // ACK all these from our mailbox to ensure that they don't get
313
        // re-delivered if we reconnect.
314
        openedCircuits []CircuitKey
315

316
        // closedCircuits is the set of all payment circuits that will be
317
        // closed once we make our next commitment. After taking the commitment
318
        // we'll ACK all these to ensure that they don't get re-delivered if we
319
        // reconnect.
320
        closedCircuits []CircuitKey
321

322
        // channel is a lightning network channel to which we apply htlc
323
        // updates.
324
        channel *lnwallet.LightningChannel
325

326
        // cfg is a structure which carries all dependable fields/handlers
327
        // which may affect behaviour of the service.
328
        cfg ChannelLinkConfig
329

330
        // mailBox is the main interface between the outside world and the
331
        // link. All incoming messages will be sent over this mailBox. Messages
332
        // include new updates from our connected peer, and new packets to be
333
        // forwarded sent by the switch.
334
        mailBox MailBox
335

336
        // upstream is a channel that new messages sent from the remote peer to
337
        // the local peer will be sent across.
338
        upstream chan lnwire.Message
339

340
        // downstream is a channel in which new multi-hop HTLC's to be
341
        // forwarded will be sent across. Messages from this channel are sent
342
        // by the HTLC switch.
343
        downstream chan *htlcPacket
344

345
        // updateFeeTimer is the timer responsible for updating the link's
346
        // commitment fee every time it fires.
347
        updateFeeTimer *time.Timer
348

349
        // uncommittedPreimages stores a list of all preimages that have been
350
        // learned since receiving the last CommitSig from the remote peer. The
351
        // batch will be flushed just before accepting the subsequent CommitSig
352
        // or on shutdown to avoid doing a write for each preimage received.
353
        uncommittedPreimages []lntypes.Preimage
354

355
        sync.RWMutex
356

357
        // hodlQueue is used to receive exit hop htlc resolutions from invoice
358
        // registry.
359
        hodlQueue *queue.ConcurrentQueue
360

361
        // hodlMap stores related htlc data for a circuit key. It allows
362
        // resolving those htlcs when we receive a message on hodlQueue.
363
        hodlMap map[models.CircuitKey]hodlHtlc
364

365
        // log is a link-specific logging instance.
366
        log btclog.Logger
367

368
        // isOutgoingAddBlocked tracks whether the channelLink can send an
369
        // UpdateAddHTLC.
370
        isOutgoingAddBlocked atomic.Bool
371

372
        // isIncomingAddBlocked tracks whether the channelLink can receive an
373
        // UpdateAddHTLC.
374
        isIncomingAddBlocked atomic.Bool
375

376
        // flushHooks is a hookMap that is triggered when we reach a channel
377
        // state with no live HTLCs.
378
        flushHooks hookMap
379

380
        // outgoingCommitHooks is a hookMap that is triggered after we send our
381
        // next CommitSig.
382
        outgoingCommitHooks hookMap
383

384
        // incomingCommitHooks is a hookMap that is triggered after we receive
385
        // our next CommitSig.
386
        incomingCommitHooks hookMap
387

388
        wg   sync.WaitGroup
389
        quit chan struct{}
390
}
391

392
// hookMap is a data structure that is used to track the hooks that need to be
393
// called in various parts of the channelLink's lifecycle.
394
//
395
// WARNING: NOT thread-safe.
396
type hookMap struct {
397
        // allocIdx keeps track of the next id we haven't yet allocated.
398
        allocIdx atomic.Uint64
399

400
        // transient is a map of hooks that are only called the next time invoke
401
        // is called. These hooks are deleted during invoke.
402
        transient map[uint64]func()
403

404
        // newTransients is a channel that we use to accept new hooks into the
405
        // hookMap.
406
        newTransients chan func()
407
}
408

409
// newHookMap initializes a new empty hookMap.
410
func newHookMap() hookMap {
643✔
411
        return hookMap{
643✔
412
                allocIdx:      atomic.Uint64{},
643✔
413
                transient:     make(map[uint64]func()),
643✔
414
                newTransients: make(chan func()),
643✔
415
        }
643✔
416
}
643✔
417

418
// alloc allocates space in the hook map for the supplied hook, the second
419
// argument determines whether it goes into the transient or persistent part
420
// of the hookMap.
421
func (m *hookMap) alloc(hook func()) uint64 {
6✔
422
        // We assume we never overflow a uint64. Seems OK.
6✔
423
        hookID := m.allocIdx.Add(1)
6✔
424
        if hookID == 0 {
6✔
425
                panic("hookMap allocIdx overflow")
×
426
        }
427
        m.transient[hookID] = hook
6✔
428

6✔
429
        return hookID
6✔
430
}
431

432
// invoke is used on a hook map to call all the registered hooks and then clear
433
// out the transient hooks so they are not called again.
434
func (m *hookMap) invoke() {
5,075✔
435
        for _, hook := range m.transient {
5,081✔
436
                hook()
6✔
437
        }
6✔
438

439
        m.transient = make(map[uint64]func())
5,075✔
440
}
441

442
// hodlHtlc contains htlc data that is required for resolution.
443
type hodlHtlc struct {
444
        pd         *lnwallet.PaymentDescriptor
445
        obfuscator hop.ErrorEncrypter
446
}
447

448
// NewChannelLink creates a new instance of a ChannelLink given a configuration
449
// and active channel that will be used to verify/apply updates to.
450
func NewChannelLink(cfg ChannelLinkConfig,
451
        channel *lnwallet.LightningChannel) ChannelLink {
217✔
452

217✔
453
        logPrefix := fmt.Sprintf("ChannelLink(%v):", channel.ChannelPoint())
217✔
454

217✔
455
        // If the max fee exposure isn't set, use the default.
217✔
456
        if cfg.MaxFeeExposure == 0 {
430✔
457
                cfg.MaxFeeExposure = DefaultMaxFeeExposure
213✔
458
        }
213✔
459

460
        return &channelLink{
217✔
461
                cfg:                 cfg,
217✔
462
                channel:             channel,
217✔
463
                hodlMap:             make(map[models.CircuitKey]hodlHtlc),
217✔
464
                hodlQueue:           queue.NewConcurrentQueue(10),
217✔
465
                log:                 build.NewPrefixLog(logPrefix, log),
217✔
466
                flushHooks:          newHookMap(),
217✔
467
                outgoingCommitHooks: newHookMap(),
217✔
468
                incomingCommitHooks: newHookMap(),
217✔
469
                quit:                make(chan struct{}),
217✔
470
        }
217✔
471
}
472

473
// A compile time check to ensure channelLink implements the ChannelLink
474
// interface.
475
var _ ChannelLink = (*channelLink)(nil)
476

477
// Start starts all helper goroutines required for the operation of the channel
478
// link.
479
//
480
// NOTE: Part of the ChannelLink interface.
481
func (l *channelLink) Start() error {
215✔
482
        if !atomic.CompareAndSwapInt32(&l.started, 0, 1) {
215✔
483
                err := fmt.Errorf("channel link(%v): already started", l)
×
484
                l.log.Warn("already started")
×
485
                return err
×
486
        }
×
487

488
        l.log.Info("starting")
215✔
489

215✔
490
        // If the config supplied watchtower client, ensure the channel is
215✔
491
        // registered before trying to use it during operation.
215✔
492
        if l.cfg.TowerClient != nil {
219✔
493
                err := l.cfg.TowerClient.RegisterChannel(
4✔
494
                        l.ChanID(), l.channel.State().ChanType,
4✔
495
                )
4✔
496
                if err != nil {
4✔
497
                        return err
×
498
                }
×
499
        }
500

501
        l.mailBox.ResetMessages()
215✔
502
        l.hodlQueue.Start()
215✔
503

215✔
504
        // Before launching the htlcManager messages, revert any circuits that
215✔
505
        // were marked open in the switch's circuit map, but did not make it
215✔
506
        // into a commitment txn. We use the next local htlc index as the cut
215✔
507
        // off point, since all indexes below that are committed. This action
215✔
508
        // is only performed if the link's final short channel ID has been
215✔
509
        // assigned, otherwise we would try to trim the htlcs belonging to the
215✔
510
        // all-zero, hop.Source ID.
215✔
511
        if l.ShortChanID() != hop.Source {
430✔
512
                localHtlcIndex, err := l.channel.NextLocalHtlcIndex()
215✔
513
                if err != nil {
215✔
514
                        return fmt.Errorf("unable to retrieve next local "+
×
515
                                "htlc index: %v", err)
×
516
                }
×
517

518
                // NOTE: This is automatically done by the switch when it
519
                // starts up, but is necessary to prevent inconsistencies in
520
                // the case that the link flaps. This is a result of a link's
521
                // life-cycle being shorter than that of the switch.
522
                chanID := l.ShortChanID()
215✔
523
                err = l.cfg.Circuits.TrimOpenCircuits(chanID, localHtlcIndex)
215✔
524
                if err != nil {
215✔
525
                        return fmt.Errorf("unable to trim circuits above "+
×
526
                                "local htlc index %d: %v", localHtlcIndex, err)
×
527
                }
×
528

529
                // Since the link is live, before we start the link we'll update
530
                // the ChainArbitrator with the set of new channel signals for
531
                // this channel.
532
                //
533
                // TODO(roasbeef): split goroutines within channel arb to avoid
534
                go func() {
430✔
535
                        signals := &contractcourt.ContractSignals{
215✔
536
                                ShortChanID: l.channel.ShortChanID(),
215✔
537
                        }
215✔
538

215✔
539
                        err := l.cfg.UpdateContractSignals(signals)
215✔
540
                        if err != nil {
215✔
541
                                l.log.Errorf("unable to update signals")
×
542
                        }
×
543
                }()
544
        }
545

546
        l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
215✔
547

215✔
548
        l.wg.Add(1)
215✔
549
        go l.htlcManager()
215✔
550

215✔
551
        return nil
215✔
552
}
553

554
// Stop gracefully stops all active helper goroutines, then waits until they've
555
// exited.
556
//
557
// NOTE: Part of the ChannelLink interface.
558
func (l *channelLink) Stop() {
216✔
559
        if !atomic.CompareAndSwapInt32(&l.shutdown, 0, 1) {
228✔
560
                l.log.Warn("already stopped")
12✔
561
                return
12✔
562
        }
12✔
563

564
        l.log.Info("stopping")
204✔
565

204✔
566
        // As the link is stopping, we are no longer interested in htlc
204✔
567
        // resolutions coming from the invoice registry.
204✔
568
        l.cfg.Registry.HodlUnsubscribeAll(l.hodlQueue.ChanIn())
204✔
569

204✔
570
        if l.cfg.ChainEvents.Cancel != nil {
208✔
571
                l.cfg.ChainEvents.Cancel()
4✔
572
        }
4✔
573

574
        // Ensure the channel for the timer is drained.
575
        if l.updateFeeTimer != nil {
408✔
576
                if !l.updateFeeTimer.Stop() {
204✔
577
                        select {
×
578
                        case <-l.updateFeeTimer.C:
×
UNCOV
579
                        default:
×
580
                        }
581
                }
582
        }
583

584
        if l.hodlQueue != nil {
408✔
585
                l.hodlQueue.Stop()
204✔
586
        }
204✔
587

588
        close(l.quit)
204✔
589
        l.wg.Wait()
204✔
590

204✔
591
        // Now that the htlcManager has completely exited, reset the packet
204✔
592
        // courier. This allows the mailbox to revaluate any lingering Adds that
204✔
593
        // were delivered but didn't make it on a commitment to be failed back
204✔
594
        // if the link is offline for an extended period of time. The error is
204✔
595
        // ignored since it can only fail when the daemon is exiting.
204✔
596
        _ = l.mailBox.ResetPackets()
204✔
597

204✔
598
        // As a final precaution, we will attempt to flush any uncommitted
204✔
599
        // preimages to the preimage cache. The preimages should be re-delivered
204✔
600
        // after channel reestablishment, however this adds an extra layer of
204✔
601
        // protection in case the peer never returns. Without this, we will be
204✔
602
        // unable to settle any contracts depending on the preimages even though
204✔
603
        // we had learned them at some point.
204✔
604
        err := l.cfg.PreimageCache.AddPreimages(l.uncommittedPreimages...)
204✔
605
        if err != nil {
204✔
UNCOV
606
                l.log.Errorf("unable to add preimages=%v to cache: %v",
×
UNCOV
607
                        l.uncommittedPreimages, err)
×
UNCOV
608
        }
×
609
}
610

611
// WaitForShutdown blocks until the link finishes shutting down, which includes
612
// termination of all dependent goroutines.
UNCOV
613
func (l *channelLink) WaitForShutdown() {
×
UNCOV
614
        l.wg.Wait()
×
UNCOV
615
}
×
616

617
// EligibleToForward returns a bool indicating if the channel is able to
618
// actively accept requests to forward HTLC's. We're able to forward HTLC's if
619
// we are eligible to update AND the channel isn't currently flushing the
620
// outgoing half of the channel.
621
func (l *channelLink) EligibleToForward() bool {
1,656✔
622
        return l.EligibleToUpdate() &&
1,656✔
623
                !l.IsFlushing(Outgoing)
1,656✔
624
}
1,656✔
625

626
// EligibleToUpdate returns a bool indicating if the channel is able to update
627
// channel state. We're able to update channel state if we know the remote
628
// party's next revocation point. Otherwise, we can't initiate new channel
629
// state. We also require that the short channel ID not be the all-zero source
630
// ID, meaning that the channel has had its ID finalized.
631
func (l *channelLink) EligibleToUpdate() bool {
1,659✔
632
        return l.channel.RemoteNextRevocation() != nil &&
1,659✔
633
                l.ShortChanID() != hop.Source &&
1,659✔
634
                l.isReestablished()
1,659✔
635
}
1,659✔
636

637
// EnableAdds sets the ChannelUpdateHandler state to allow UpdateAddHtlc's in
638
// the specified direction. It returns true if the state was changed and false
639
// if the desired state was already set before the method was called.
640
func (l *channelLink) EnableAdds(linkDirection LinkDirection) bool {
14✔
641
        if linkDirection == Outgoing {
21✔
642
                return l.isOutgoingAddBlocked.Swap(false)
7✔
643
        }
7✔
644

645
        return l.isIncomingAddBlocked.Swap(false)
7✔
646
}
647

648
// DisableAdds sets the ChannelUpdateHandler state to allow UpdateAddHtlc's in
649
// the specified direction. It returns true if the state was changed and false
650
// if the desired state was already set before the method was called.
651
func (l *channelLink) DisableAdds(linkDirection LinkDirection) bool {
19✔
652
        if linkDirection == Outgoing {
31✔
653
                return !l.isOutgoingAddBlocked.Swap(true)
12✔
654
        }
12✔
655

656
        return !l.isIncomingAddBlocked.Swap(true)
11✔
657
}
658

659
// IsFlushing returns true when UpdateAddHtlc's are disabled in the direction of
660
// the argument.
661
func (l *channelLink) IsFlushing(linkDirection LinkDirection) bool {
4,714✔
662
        if linkDirection == Outgoing {
7,914✔
663
                return l.isOutgoingAddBlocked.Load()
3,200✔
664
        }
3,200✔
665

666
        return l.isIncomingAddBlocked.Load()
1,518✔
667
}
668

669
// OnFlushedOnce adds a hook that will be called the next time the channel
670
// state reaches zero htlcs. This hook will only ever be called once. If the
671
// channel state already has zero htlcs, then this will be called immediately.
672
func (l *channelLink) OnFlushedOnce(hook func()) {
5✔
673
        select {
5✔
674
        case l.flushHooks.newTransients <- hook:
5✔
UNCOV
675
        case <-l.quit:
×
676
        }
677
}
678

679
// OnCommitOnce adds a hook that will be called the next time a CommitSig
680
// message is sent in the argument's LinkDirection. This hook will only ever be
681
// called once. If no CommitSig is owed in the argument's LinkDirection, then
682
// we will call this hook be run immediately.
683
func (l *channelLink) OnCommitOnce(direction LinkDirection, hook func()) {
5✔
684
        var queue chan func()
5✔
685

5✔
686
        if direction == Outgoing {
10✔
687
                queue = l.outgoingCommitHooks.newTransients
5✔
688
        } else {
5✔
UNCOV
689
                queue = l.incomingCommitHooks.newTransients
×
690
        }
×
691

692
        select {
5✔
693
        case queue <- hook:
5✔
UNCOV
694
        case <-l.quit:
×
695
        }
696
}
697

698
// isReestablished returns true if the link has successfully completed the
699
// channel reestablishment dance.
700
func (l *channelLink) isReestablished() bool {
1,659✔
701
        return atomic.LoadInt32(&l.reestablished) == 1
1,659✔
702
}
1,659✔
703

704
// markReestablished signals that the remote peer has successfully exchanged
705
// channel reestablish messages and that the channel is ready to process
706
// subsequent messages.
707
func (l *channelLink) markReestablished() {
215✔
708
        atomic.StoreInt32(&l.reestablished, 1)
215✔
709
}
215✔
710

711
// IsUnadvertised returns true if the underlying channel is unadvertised.
712
func (l *channelLink) IsUnadvertised() bool {
6✔
713
        state := l.channel.State()
6✔
714
        return state.ChannelFlags&lnwire.FFAnnounceChannel == 0
6✔
715
}
6✔
716

717
// sampleNetworkFee samples the current fee rate on the network to get into the
718
// chain in a timely manner. The returned value is expressed in fee-per-kw, as
719
// this is the native rate used when computing the fee for commitment
720
// transactions, and the second-level HTLC transactions.
721
func (l *channelLink) sampleNetworkFee() (chainfee.SatPerKWeight, error) {
4✔
722
        // We'll first query for the sat/kw recommended to be confirmed within 3
4✔
723
        // blocks.
4✔
724
        feePerKw, err := l.cfg.FeeEstimator.EstimateFeePerKW(3)
4✔
725
        if err != nil {
4✔
UNCOV
726
                return 0, err
×
UNCOV
727
        }
×
728

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

4✔
732
        return feePerKw, nil
4✔
733
}
734

735
// shouldAdjustCommitFee returns true if we should update our commitment fee to
736
// match that of the network fee. We'll only update our commitment fee if the
737
// network fee is +/- 10% to our commitment fee or if our current commitment
738
// fee is below the minimum relay fee.
739
func shouldAdjustCommitFee(netFee, chanFee,
740
        minRelayFee chainfee.SatPerKWeight) bool {
14✔
741

14✔
742
        switch {
14✔
743
        // If the network fee is greater than our current commitment fee and
744
        // our current commitment fee is below the minimum relay fee then
745
        // we should switch to it no matter if it is less than a 10% increase.
746
        case netFee > chanFee && chanFee < minRelayFee:
1✔
747
                return true
1✔
748

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

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

759
        // Otherwise, we won't modify our fee.
760
        default:
7✔
761
                return false
7✔
762
        }
763
}
764

765
// failCb is used to cut down on the argument verbosity.
766
type failCb func(update *lnwire.ChannelUpdate) lnwire.FailureMessage
767

768
// createFailureWithUpdate creates a ChannelUpdate when failing an incoming or
769
// outgoing HTLC. It may return a FailureMessage that references a channel's
770
// alias. If the channel does not have an alias, then the regular channel
771
// update from disk will be returned.
772
func (l *channelLink) createFailureWithUpdate(incoming bool,
773
        outgoingScid lnwire.ShortChannelID, cb failCb) lnwire.FailureMessage {
26✔
774

26✔
775
        // Determine which SCID to use in case we need to use aliases in the
26✔
776
        // ChannelUpdate.
26✔
777
        scid := outgoingScid
26✔
778
        if incoming {
26✔
UNCOV
779
                scid = l.ShortChanID()
×
UNCOV
780
        }
×
781

782
        // Try using the FailAliasUpdate function. If it returns nil, fallback
783
        // to the non-alias behavior.
784
        update := l.cfg.FailAliasUpdate(scid, incoming)
26✔
785
        if update == nil {
46✔
786
                // Fallback to the non-alias behavior.
20✔
787
                var err error
20✔
788
                update, err = l.cfg.FetchLastChannelUpdate(l.ShortChanID())
20✔
789
                if err != nil {
20✔
UNCOV
790
                        return &lnwire.FailTemporaryNodeFailure{}
×
UNCOV
791
                }
×
792
        }
793

794
        return cb(update)
26✔
795
}
796

797
// syncChanState attempts to synchronize channel states with the remote party.
798
// This method is to be called upon reconnection after the initial funding
799
// flow. We'll compare out commitment chains with the remote party, and re-send
800
// either a danging commit signature, a revocation, or both.
801
func (l *channelLink) syncChanStates() error {
172✔
802
        chanState := l.channel.State()
172✔
803

172✔
804
        l.log.Infof("Attempting to re-synchronize channel: %v", chanState)
172✔
805

172✔
806
        // First, we'll generate our ChanSync message to send to the other
172✔
807
        // side. Based on this message, the remote party will decide if they
172✔
808
        // need to retransmit any data or not.
172✔
809
        localChanSyncMsg, err := chanState.ChanSyncMsg()
172✔
810
        if err != nil {
172✔
811
                return fmt.Errorf("unable to generate chan sync message for "+
×
812
                        "ChannelPoint(%v)", l.channel.ChannelPoint())
×
813
        }
×
814
        if err := l.cfg.Peer.SendMessage(true, localChanSyncMsg); err != nil {
172✔
UNCOV
815
                return fmt.Errorf("unable to send chan sync message for "+
×
UNCOV
816
                        "ChannelPoint(%v): %v", l.channel.ChannelPoint(), err)
×
UNCOV
817
        }
×
818

819
        var msgsToReSend []lnwire.Message
172✔
820

172✔
821
        // Next, we'll wait indefinitely to receive the ChanSync message. The
172✔
822
        // first message sent MUST be the ChanSync message.
172✔
823
        select {
172✔
824
        case msg := <-l.upstream:
172✔
825
                l.log.Tracef("Received msg=%v from peer(%x)", msg.MsgType(),
172✔
826
                        l.cfg.Peer.PubKey())
172✔
827

172✔
828
                remoteChanSyncMsg, ok := msg.(*lnwire.ChannelReestablish)
172✔
829
                if !ok {
172✔
UNCOV
830
                        return fmt.Errorf("first message sent to sync "+
×
UNCOV
831
                                "should be ChannelReestablish, instead "+
×
UNCOV
832
                                "received: %T", msg)
×
UNCOV
833
                }
×
834

835
                // If the remote party indicates that they think we haven't
836
                // done any state updates yet, then we'll retransmit the
837
                // channel_ready message first. We do this, as at this point
838
                // we can't be sure if they've really received the
839
                // ChannelReady message.
840
                if remoteChanSyncMsg.NextLocalCommitHeight == 1 &&
172✔
841
                        localChanSyncMsg.NextLocalCommitHeight == 1 &&
172✔
842
                        !l.channel.IsPending() {
338✔
843

166✔
844
                        l.log.Infof("resending ChannelReady message to peer")
166✔
845

166✔
846
                        nextRevocation, err := l.channel.NextRevocationKey()
166✔
847
                        if err != nil {
166✔
UNCOV
848
                                return fmt.Errorf("unable to create next "+
×
UNCOV
849
                                        "revocation: %v", err)
×
UNCOV
850
                        }
×
851

852
                        channelReadyMsg := lnwire.NewChannelReady(
166✔
853
                                l.ChanID(), nextRevocation,
166✔
854
                        )
166✔
855

166✔
856
                        // If this is a taproot channel, then we'll send the
166✔
857
                        // very same nonce that we sent above, as they should
166✔
858
                        // take the latest verification nonce we send.
166✔
859
                        if chanState.ChanType.IsTaproot() {
170✔
860
                                //nolint:lll
4✔
861
                                channelReadyMsg.NextLocalNonce = localChanSyncMsg.LocalNonce
4✔
862
                        }
4✔
863

864
                        // For channels that negotiated the option-scid-alias
865
                        // feature bit, ensure that we send over the alias in
866
                        // the channel_ready message. We'll send the first
867
                        // alias we find for the channel since it does not
868
                        // matter which alias we send. We'll error out if no
869
                        // aliases are found.
870
                        if l.negotiatedAliasFeature() {
170✔
871
                                aliases := l.getAliases()
4✔
872
                                if len(aliases) == 0 {
4✔
873
                                        // This shouldn't happen since we
×
UNCOV
874
                                        // always add at least one alias before
×
UNCOV
875
                                        // the channel reaches the link.
×
UNCOV
876
                                        return fmt.Errorf("no aliases found")
×
UNCOV
877
                                }
×
878

879
                                // getAliases returns a copy of the alias slice
880
                                // so it is ok to use a pointer to the first
881
                                // entry.
882
                                channelReadyMsg.AliasScid = &aliases[0]
4✔
883
                        }
884

885
                        err = l.cfg.Peer.SendMessage(false, channelReadyMsg)
166✔
886
                        if err != nil {
166✔
UNCOV
887
                                return fmt.Errorf("unable to re-send "+
×
UNCOV
888
                                        "ChannelReady: %v", err)
×
UNCOV
889
                        }
×
890
                }
891

892
                // In any case, we'll then process their ChanSync message.
893
                l.log.Info("received re-establishment message from remote side")
172✔
894

172✔
895
                var (
172✔
896
                        openedCircuits []CircuitKey
172✔
897
                        closedCircuits []CircuitKey
172✔
898
                )
172✔
899

172✔
900
                // We've just received a ChanSync message from the remote
172✔
901
                // party, so we'll process the message  in order to determine
172✔
902
                // if we need to re-transmit any messages to the remote party.
172✔
903
                msgsToReSend, openedCircuits, closedCircuits, err =
172✔
904
                        l.channel.ProcessChanSyncMsg(remoteChanSyncMsg)
172✔
905
                if err != nil {
176✔
906
                        return err
4✔
907
                }
4✔
908

909
                // Repopulate any identifiers for circuits that may have been
910
                // opened or unclosed. This may happen if we needed to
911
                // retransmit a commitment signature message.
912
                l.openedCircuits = openedCircuits
172✔
913
                l.closedCircuits = closedCircuits
172✔
914

172✔
915
                // Ensure that all packets have been have been removed from the
172✔
916
                // link's mailbox.
172✔
917
                if err := l.ackDownStreamPackets(); err != nil {
172✔
UNCOV
918
                        return err
×
UNCOV
919
                }
×
920

921
                if len(msgsToReSend) > 0 {
177✔
922
                        l.log.Infof("sending %v updates to synchronize the "+
5✔
923
                                "state", len(msgsToReSend))
5✔
924
                }
5✔
925

926
                // If we have any messages to retransmit, we'll do so
927
                // immediately so we return to a synchronized state as soon as
928
                // possible.
929
                for _, msg := range msgsToReSend {
183✔
930
                        l.cfg.Peer.SendMessage(false, msg)
11✔
931
                }
11✔
932

933
        case <-l.quit:
4✔
934
                return ErrLinkShuttingDown
4✔
935
        }
936

937
        return nil
172✔
938
}
939

940
// resolveFwdPkgs loads any forwarding packages for this link from disk, and
941
// reprocesses them in order. The primary goal is to make sure that any HTLCs
942
// we previously received are reinstated in memory, and forwarded to the switch
943
// if necessary. After a restart, this will also delete any previously
944
// completed packages.
945
func (l *channelLink) resolveFwdPkgs() error {
215✔
946
        fwdPkgs, err := l.channel.LoadFwdPkgs()
215✔
947
        if err != nil {
215✔
UNCOV
948
                return err
×
UNCOV
949
        }
×
950

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

215✔
953
        for _, fwdPkg := range fwdPkgs {
225✔
954
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
11✔
955
                        return err
1✔
956
                }
1✔
957
        }
958

959
        // If any of our reprocessing steps require an update to the commitment
960
        // txn, we initiate a state transition to capture all relevant changes.
961
        if l.channel.PendingLocalUpdateCount() > 0 {
219✔
962
                return l.updateCommitTx()
4✔
963
        }
4✔
964

965
        return nil
215✔
966
}
967

968
// resolveFwdPkg interprets the FwdState of the provided package, either
969
// reprocesses any outstanding htlcs in the package, or performs garbage
970
// collection on the package.
971
func (l *channelLink) resolveFwdPkg(fwdPkg *channeldb.FwdPkg) error {
10✔
972
        // Remove any completed packages to clear up space.
10✔
973
        if fwdPkg.State == channeldb.FwdStateCompleted {
15✔
974
                l.log.Debugf("removing completed fwd pkg for height=%d",
5✔
975
                        fwdPkg.Height)
5✔
976

5✔
977
                err := l.channel.RemoveFwdPkgs(fwdPkg.Height)
5✔
978
                if err != nil {
6✔
979
                        l.log.Errorf("unable to remove fwd pkg for height=%d: "+
1✔
980
                                "%v", fwdPkg.Height, err)
1✔
981
                        return err
1✔
982
                }
1✔
983
        }
984

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

991
        // If the package is fully acked but not completed, it must still have
992
        // settles and fails to propagate.
993
        if !fwdPkg.SettleFailFilter.IsFull() {
14✔
994
                settleFails, err := lnwallet.PayDescsFromRemoteLogUpdates(
4✔
995
                        fwdPkg.Source, fwdPkg.Height, fwdPkg.SettleFails,
4✔
996
                )
4✔
997
                if err != nil {
4✔
UNCOV
998
                        l.log.Errorf("unable to process remote log updates: %v",
×
UNCOV
999
                                err)
×
UNCOV
1000
                        return err
×
UNCOV
1001
                }
×
1002
                l.processRemoteSettleFails(fwdPkg, settleFails)
4✔
1003
        }
1004

1005
        // Finally, replay *ALL ADDS* in this forwarding package. The
1006
        // downstream logic is able to filter out any duplicates, but we must
1007
        // shove the entire, original set of adds down the pipeline so that the
1008
        // batch of adds presented to the sphinx router does not ever change.
1009
        if !fwdPkg.AckFilter.IsFull() {
17✔
1010
                adds, err := lnwallet.PayDescsFromRemoteLogUpdates(
7✔
1011
                        fwdPkg.Source, fwdPkg.Height, fwdPkg.Adds,
7✔
1012
                )
7✔
1013
                if err != nil {
7✔
UNCOV
1014
                        l.log.Errorf("unable to process remote log updates: %v",
×
UNCOV
1015
                                err)
×
UNCOV
1016
                        return err
×
UNCOV
1017
                }
×
1018
                l.processRemoteAdds(fwdPkg, adds)
7✔
1019

7✔
1020
                // If the link failed during processing the adds, we must
7✔
1021
                // return to ensure we won't attempted to update the state
7✔
1022
                // further.
7✔
1023
                if l.failed {
7✔
UNCOV
1024
                        return fmt.Errorf("link failed while " +
×
UNCOV
1025
                                "processing remote adds")
×
UNCOV
1026
                }
×
1027
        }
1028

1029
        return nil
10✔
1030
}
1031

1032
// fwdPkgGarbager periodically reads all forwarding packages from disk and
1033
// removes those that can be discarded. It is safe to do this entirely in the
1034
// background, since all state is coordinated on disk. This also ensures the
1035
// link can continue to process messages and interleave database accesses.
1036
//
1037
// NOTE: This MUST be run as a goroutine.
1038
func (l *channelLink) fwdPkgGarbager() {
215✔
1039
        defer l.wg.Done()
215✔
1040

215✔
1041
        l.cfg.FwdPkgGCTicker.Resume()
215✔
1042
        defer l.cfg.FwdPkgGCTicker.Stop()
215✔
1043

215✔
1044
        if err := l.loadAndRemove(); err != nil {
215✔
UNCOV
1045
                l.log.Warnf("unable to run initial fwd pkgs gc: %v", err)
×
UNCOV
1046
        }
×
1047

1048
        for {
506✔
1049
                select {
291✔
1050
                case <-l.cfg.FwdPkgGCTicker.Ticks():
76✔
1051
                        if err := l.loadAndRemove(); err != nil {
140✔
1052
                                l.log.Warnf("unable to remove fwd pkgs: %v",
64✔
1053
                                        err)
64✔
1054
                                continue
64✔
1055
                        }
1056
                case <-l.quit:
204✔
1057
                        return
204✔
1058
                }
1059
        }
1060
}
1061

1062
// loadAndRemove loads all the channels forwarding packages and determines if
1063
// they can be removed. It is called once before the FwdPkgGCTicker ticks so that
1064
// a longer tick interval can be used.
1065
func (l *channelLink) loadAndRemove() error {
291✔
1066
        fwdPkgs, err := l.channel.LoadFwdPkgs()
291✔
1067
        if err != nil {
355✔
1068
                return err
64✔
1069
        }
64✔
1070

1071
        var removeHeights []uint64
227✔
1072
        for _, fwdPkg := range fwdPkgs {
1,235✔
1073
                if fwdPkg.State != channeldb.FwdStateCompleted {
1,126✔
1074
                        continue
118✔
1075
                }
1076

1077
                removeHeights = append(removeHeights, fwdPkg.Height)
894✔
1078
        }
1079

1080
        // If removeHeights is empty, return early so we don't use a db
1081
        // transaction.
1082
        if len(removeHeights) == 0 {
443✔
1083
                return nil
216✔
1084
        }
216✔
1085

1086
        return l.channel.RemoveFwdPkgs(removeHeights...)
15✔
1087
}
1088

1089
// htlcManager is the primary goroutine which drives a channel's commitment
1090
// update state-machine in response to messages received via several channels.
1091
// This goroutine reads messages from the upstream (remote) peer, and also from
1092
// downstream channel managed by the channel link. In the event that an htlc
1093
// needs to be forwarded, then send-only forward handler is used which sends
1094
// htlc packets to the switch. Additionally, this goroutine handles acting upon
1095
// all timeouts for any active HTLCs, manages the channel's revocation window,
1096
// and also the htlc trickle queue+timer for this active channels.
1097
//
1098
// NOTE: This MUST be run as a goroutine.
1099
func (l *channelLink) htlcManager() {
215✔
1100
        defer func() {
421✔
1101
                l.cfg.BatchTicker.Stop()
206✔
1102
                l.wg.Done()
206✔
1103
                l.log.Infof("exited")
206✔
1104
        }()
206✔
1105

1106
        l.log.Infof("HTLC manager started, bandwidth=%v", l.Bandwidth())
215✔
1107

215✔
1108
        // Notify any clients that the link is now in the switch via an
215✔
1109
        // ActiveLinkEvent. We'll also defer an inactive link notification for
215✔
1110
        // when the link exits to ensure that every active notification is
215✔
1111
        // matched by an inactive one.
215✔
1112
        l.cfg.NotifyActiveLink(l.ChannelPoint())
215✔
1113
        defer l.cfg.NotifyInactiveLinkEvent(l.ChannelPoint())
215✔
1114

215✔
1115
        // TODO(roasbeef): need to call wipe chan whenever D/C?
215✔
1116

215✔
1117
        // If this isn't the first time that this channel link has been
215✔
1118
        // created, then we'll need to check to see if we need to
215✔
1119
        // re-synchronize state with the remote peer. settledHtlcs is a map of
215✔
1120
        // HTLC's that we re-settled as part of the channel state sync.
215✔
1121
        if l.cfg.SyncStates {
387✔
1122
                err := l.syncChanStates()
172✔
1123
                if err != nil {
176✔
1124
                        l.log.Warnf("error when syncing channel states: %v", err)
4✔
1125

4✔
1126
                        errDataLoss, localDataLoss :=
4✔
1127
                                err.(*lnwallet.ErrCommitSyncLocalDataLoss)
4✔
1128

4✔
1129
                        switch {
4✔
1130
                        case err == ErrLinkShuttingDown:
4✔
1131
                                l.log.Debugf("unable to sync channel states, " +
4✔
1132
                                        "link is shutting down")
4✔
1133
                                return
4✔
1134

1135
                        // We failed syncing the commit chains, probably
1136
                        // because the remote has lost state. We should force
1137
                        // close the channel.
1138
                        case err == lnwallet.ErrCommitSyncRemoteDataLoss:
4✔
1139
                                fallthrough
4✔
1140

1141
                        // The remote sent us an invalid last commit secret, we
1142
                        // should force close the channel.
1143
                        // TODO(halseth): and permanently ban the peer?
1144
                        case err == lnwallet.ErrInvalidLastCommitSecret:
4✔
1145
                                fallthrough
4✔
1146

1147
                        // The remote sent us a commit point different from
1148
                        // what they sent us before.
1149
                        // TODO(halseth): ban peer?
1150
                        case err == lnwallet.ErrInvalidLocalUnrevokedCommitPoint:
4✔
1151
                                // We'll fail the link and tell the peer to
4✔
1152
                                // force close the channel. Note that the
4✔
1153
                                // database state is not updated here, but will
4✔
1154
                                // be updated when the close transaction is
4✔
1155
                                // ready to avoid that we go down before
4✔
1156
                                // storing the transaction in the db.
4✔
1157
                                l.fail(
4✔
1158
                                        LinkFailureError{
4✔
1159
                                                code:          ErrSyncError,
4✔
1160
                                                FailureAction: LinkFailureForceClose, //nolint:lll
4✔
1161
                                        },
4✔
1162
                                        "unable to synchronize channel "+
4✔
1163
                                                "states: %v", err,
4✔
1164
                                )
4✔
1165
                                return
4✔
1166

1167
                        // We have lost state and cannot safely force close the
1168
                        // channel. Fail the channel and wait for the remote to
1169
                        // hopefully force close it. The remote has sent us its
1170
                        // latest unrevoked commitment point, and we'll store
1171
                        // it in the database, such that we can attempt to
1172
                        // recover the funds if the remote force closes the
1173
                        // channel.
1174
                        case localDataLoss:
4✔
1175
                                err := l.channel.MarkDataLoss(
4✔
1176
                                        errDataLoss.CommitPoint,
4✔
1177
                                )
4✔
1178
                                if err != nil {
4✔
UNCOV
1179
                                        l.log.Errorf("unable to mark channel "+
×
UNCOV
1180
                                                "data loss: %v", err)
×
UNCOV
1181
                                }
×
1182

1183
                        // We determined the commit chains were not possible to
1184
                        // sync. We cautiously fail the channel, but don't
1185
                        // force close.
1186
                        // TODO(halseth): can we safely force close in any
1187
                        // cases where this error is returned?
1188
                        case err == lnwallet.ErrCannotSyncCommitChains:
×
UNCOV
1189
                                if err := l.channel.MarkBorked(); err != nil {
×
UNCOV
1190
                                        l.log.Errorf("unable to mark channel "+
×
1191
                                                "borked: %v", err)
×
UNCOV
1192
                                }
×
1193

1194
                        // Other, unspecified error.
UNCOV
1195
                        default:
×
1196
                        }
1197

1198
                        l.fail(
4✔
1199
                                LinkFailureError{
4✔
1200
                                        code:          ErrRecoveryError,
4✔
1201
                                        FailureAction: LinkFailureForceNone,
4✔
1202
                                },
4✔
1203
                                "unable to synchronize channel "+
4✔
1204
                                        "states: %v", err,
4✔
1205
                        )
4✔
1206
                        return
4✔
1207
                }
1208
        }
1209

1210
        // If a shutdown message has previously been sent on this link, then we
1211
        // need to make sure that we have disabled any HTLC adds on the outgoing
1212
        // direction of the link and that we re-resend the same shutdown message
1213
        // that we previously sent.
1214
        l.cfg.PreviouslySentShutdown.WhenSome(func(shutdown lnwire.Shutdown) {
219✔
1215
                // Immediately disallow any new outgoing HTLCs.
4✔
1216
                if !l.DisableAdds(Outgoing) {
4✔
UNCOV
1217
                        l.log.Warnf("Outgoing link adds already disabled")
×
UNCOV
1218
                }
×
1219

1220
                // Re-send the shutdown message the peer. Since syncChanStates
1221
                // would have sent any outstanding CommitSig, it is fine for us
1222
                // to immediately queue the shutdown message now.
1223
                err := l.cfg.Peer.SendMessage(false, &shutdown)
4✔
1224
                if err != nil {
4✔
UNCOV
1225
                        l.log.Warnf("Error sending shutdown message: %v", err)
×
UNCOV
1226
                }
×
1227
        })
1228

1229
        // We've successfully reestablished the channel, mark it as such to
1230
        // allow the switch to forward HTLCs in the outbound direction.
1231
        l.markReestablished()
215✔
1232

215✔
1233
        // Now that we've received both channel_ready and channel reestablish,
215✔
1234
        // we can go ahead and send the active channel notification. We'll also
215✔
1235
        // defer the inactive notification for when the link exits to ensure
215✔
1236
        // that every active notification is matched by an inactive one.
215✔
1237
        l.cfg.NotifyActiveChannel(l.ChannelPoint())
215✔
1238
        defer l.cfg.NotifyInactiveChannel(l.ChannelPoint())
215✔
1239

215✔
1240
        // With the channel states synced, we now reset the mailbox to ensure
215✔
1241
        // we start processing all unacked packets in order. This is done here
215✔
1242
        // to ensure that all acknowledgments that occur during channel
215✔
1243
        // resynchronization have taken affect, causing us only to pull unacked
215✔
1244
        // packets after starting to read from the downstream mailbox.
215✔
1245
        l.mailBox.ResetPackets()
215✔
1246

215✔
1247
        // After cleaning up any memory pertaining to incoming packets, we now
215✔
1248
        // replay our forwarding packages to handle any htlcs that can be
215✔
1249
        // processed locally, or need to be forwarded out to the switch. We will
215✔
1250
        // only attempt to resolve packages if our short chan id indicates that
215✔
1251
        // the channel is not pending, otherwise we should have no htlcs to
215✔
1252
        // reforward.
215✔
1253
        if l.ShortChanID() != hop.Source {
430✔
1254
                err := l.resolveFwdPkgs()
215✔
1255
                switch err {
215✔
1256
                // No error was encountered, success.
1257
                case nil:
215✔
1258

1259
                // If the duplicate keystone error was encountered, we'll fail
1260
                // without sending an Error message to the peer.
UNCOV
1261
                case ErrDuplicateKeystone:
×
UNCOV
1262
                        l.fail(LinkFailureError{code: ErrCircuitError},
×
UNCOV
1263
                                "temporary circuit error: %v", err)
×
1264
                        return
×
1265

1266
                // A non-nil error was encountered, send an Error message to
1267
                // the peer.
1268
                default:
1✔
1269
                        l.fail(LinkFailureError{code: ErrInternalError},
1✔
1270
                                "unable to resolve fwd pkgs: %v", err)
1✔
1271
                        return
1✔
1272
                }
1273

1274
                // With our link's in-memory state fully reconstructed, spawn a
1275
                // goroutine to manage the reclamation of disk space occupied by
1276
                // completed forwarding packages.
1277
                l.wg.Add(1)
215✔
1278
                go l.fwdPkgGarbager()
215✔
1279
        }
1280

1281
        for {
9,690✔
1282
                // We must always check if we failed at some point processing
9,475✔
1283
                // the last update before processing the next.
9,475✔
1284
                if l.failed {
9,488✔
1285
                        l.log.Errorf("link failed, exiting htlcManager")
13✔
1286
                        return
13✔
1287
                }
13✔
1288

1289
                // If the previous event resulted in a non-empty batch, resume
1290
                // the batch ticker so that it can be cleared. Otherwise pause
1291
                // the ticker to prevent waking up the htlcManager while the
1292
                // batch is empty.
1293
                if l.channel.PendingLocalUpdateCount() > 0 {
11,190✔
1294
                        l.cfg.BatchTicker.Resume()
1,724✔
1295
                        l.log.Tracef("BatchTicker resumed, "+
1,724✔
1296
                                "PendingLocalUpdateCount=%d",
1,724✔
1297
                                l.channel.PendingLocalUpdateCount())
1,724✔
1298
                } else {
9,470✔
1299
                        l.cfg.BatchTicker.Pause()
7,746✔
1300
                        l.log.Trace("BatchTicker paused due to zero " +
7,746✔
1301
                                "PendingLocalUpdateCount")
7,746✔
1302
                }
7,746✔
1303

1304
                select {
9,466✔
1305
                // We have a new hook that needs to be run when we reach a clean
1306
                // channel state.
1307
                case hook := <-l.flushHooks.newTransients:
5✔
1308
                        if l.channel.IsChannelClean() {
9✔
1309
                                hook()
4✔
1310
                        } else {
9✔
1311
                                l.flushHooks.alloc(hook)
5✔
1312
                        }
5✔
1313

1314
                // We have a new hook that needs to be run when we have
1315
                // committed all of our updates.
1316
                case hook := <-l.outgoingCommitHooks.newTransients:
5✔
1317
                        if !l.channel.OweCommitment() {
9✔
1318
                                hook()
4✔
1319
                        } else {
5✔
1320
                                l.outgoingCommitHooks.alloc(hook)
1✔
1321
                        }
1✔
1322

1323
                // We have a new hook that needs to be run when our peer has
1324
                // committed all of their updates.
1325
                case hook := <-l.incomingCommitHooks.newTransients:
×
1326
                        if !l.channel.NeedCommitment() {
×
UNCOV
1327
                                hook()
×
UNCOV
1328
                        } else {
×
UNCOV
1329
                                l.incomingCommitHooks.alloc(hook)
×
UNCOV
1330
                        }
×
1331

1332
                // Our update fee timer has fired, so we'll check the network
1333
                // fee to see if we should adjust our commitment fee.
1334
                case <-l.updateFeeTimer.C:
4✔
1335
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
4✔
1336

4✔
1337
                        // If we're not the initiator of the channel, don't we
4✔
1338
                        // don't control the fees, so we can ignore this.
4✔
1339
                        if !l.channel.IsInitiator() {
4✔
UNCOV
1340
                                continue
×
1341
                        }
1342

1343
                        // If we are the initiator, then we'll sample the
1344
                        // current fee rate to get into the chain within 3
1345
                        // blocks.
1346
                        netFee, err := l.sampleNetworkFee()
4✔
1347
                        if err != nil {
4✔
UNCOV
1348
                                l.log.Errorf("unable to sample network fee: %v",
×
UNCOV
1349
                                        err)
×
UNCOV
1350
                                continue
×
1351
                        }
1352

1353
                        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
4✔
1354

4✔
1355
                        newCommitFee := l.channel.IdealCommitFeeRate(
4✔
1356
                                netFee, minRelayFee,
4✔
1357
                                l.cfg.MaxAnchorsCommitFeeRate,
4✔
1358
                                l.cfg.MaxFeeAllocation,
4✔
1359
                        )
4✔
1360

4✔
1361
                        // We determine if we should adjust the commitment fee
4✔
1362
                        // based on the current commitment fee, the suggested
4✔
1363
                        // new commitment fee and the current minimum relay fee
4✔
1364
                        // rate.
4✔
1365
                        commitFee := l.channel.CommitFeeRate()
4✔
1366
                        if !shouldAdjustCommitFee(
4✔
1367
                                newCommitFee, commitFee, minRelayFee,
4✔
1368
                        ) {
5✔
1369

1✔
1370
                                continue
1✔
1371
                        }
1372

1373
                        // If we do, then we'll send a new UpdateFee message to
1374
                        // the remote party, to be locked in with a new update.
1375
                        if err := l.updateChannelFee(newCommitFee); err != nil {
3✔
UNCOV
1376
                                l.log.Errorf("unable to update fee rate: %v",
×
UNCOV
1377
                                        err)
×
UNCOV
1378
                                continue
×
1379
                        }
1380

1381
                // The underlying channel has notified us of a unilateral close
1382
                // carried out by the remote peer. In the case of such an
1383
                // event, we'll wipe the channel state from the peer, and mark
1384
                // the contract as fully settled. Afterwards we can exit.
1385
                //
1386
                // TODO(roasbeef): add force closure? also breach?
1387
                case <-l.cfg.ChainEvents.RemoteUnilateralClosure:
4✔
1388
                        l.log.Warnf("remote peer has closed on-chain")
4✔
1389

4✔
1390
                        // TODO(roasbeef): remove all together
4✔
1391
                        go func() {
8✔
1392
                                chanPoint := l.channel.ChannelPoint()
4✔
1393
                                l.cfg.Peer.WipeChannel(&chanPoint)
4✔
1394
                        }()
4✔
1395

1396
                        return
4✔
1397

1398
                case <-l.cfg.BatchTicker.Ticks():
265✔
1399
                        // Attempt to extend the remote commitment chain
265✔
1400
                        // including all the currently pending entries. If the
265✔
1401
                        // send was unsuccessful, then abandon the update,
265✔
1402
                        // waiting for the revocation window to open up.
265✔
1403
                        if !l.updateCommitTxOrFail() {
265✔
UNCOV
1404
                                return
×
UNCOV
1405
                        }
×
1406

1407
                case <-l.cfg.PendingCommitTicker.Ticks():
2✔
1408
                        l.fail(
2✔
1409
                                LinkFailureError{
2✔
1410
                                        code:          ErrRemoteUnresponsive,
2✔
1411
                                        FailureAction: LinkFailureDisconnect,
2✔
1412
                                },
2✔
1413
                                "unable to complete dance",
2✔
1414
                        )
2✔
1415
                        return
2✔
1416

1417
                // A message from the switch was just received. This indicates
1418
                // that the link is an intermediate hop in a multi-hop HTLC
1419
                // circuit.
1420
                case pkt := <-l.downstream:
1,565✔
1421
                        l.handleDownstreamPkt(pkt)
1,565✔
1422

1423
                // A message from the connected peer was just received. This
1424
                // indicates that we have a new incoming HTLC, either directly
1425
                // for us, or part of a multi-hop HTLC circuit.
1426
                case msg := <-l.upstream:
6,948✔
1427
                        l.handleUpstreamMsg(msg)
6,948✔
1428

1429
                // A htlc resolution is received. This means that we now have a
1430
                // resolution for a previously accepted htlc.
1431
                case hodlItem := <-l.hodlQueue.ChanOut():
492✔
1432
                        htlcResolution := hodlItem.(invoices.HtlcResolution)
492✔
1433
                        err := l.processHodlQueue(htlcResolution)
492✔
1434
                        switch err {
492✔
1435
                        // No error, success.
1436
                        case nil:
491✔
1437

1438
                        // If the duplicate keystone error was encountered,
1439
                        // fail back gracefully.
1440
                        case ErrDuplicateKeystone:
×
1441
                                l.fail(LinkFailureError{code: ErrCircuitError},
×
1442
                                        fmt.Sprintf("process hodl queue: "+
×
UNCOV
1443
                                                "temporary circuit error: %v",
×
UNCOV
1444
                                                err,
×
UNCOV
1445
                                        ),
×
UNCOV
1446
                                )
×
1447

1448
                        // Send an Error message to the peer.
1449
                        default:
1✔
1450
                                l.fail(LinkFailureError{code: ErrInternalError},
1✔
1451
                                        fmt.Sprintf("process hodl queue: "+
1✔
1452
                                                "unable to update commitment:"+
1✔
1453
                                                " %v", err),
1✔
1454
                                )
1✔
1455
                        }
1456

1457
                case <-l.quit:
195✔
1458
                        return
195✔
1459
                }
1460
        }
1461
}
1462

1463
// processHodlQueue processes a received htlc resolution and continues reading
1464
// from the hodl queue until no more resolutions remain. When this function
1465
// returns without an error, the commit tx should be updated.
1466
func (l *channelLink) processHodlQueue(
1467
        firstResolution invoices.HtlcResolution) error {
492✔
1468

492✔
1469
        // Try to read all waiting resolution messages, so that they can all be
492✔
1470
        // processed in a single commitment tx update.
492✔
1471
        htlcResolution := firstResolution
492✔
1472
loop:
492✔
1473
        for {
984✔
1474
                // Lookup all hodl htlcs that can be failed or settled with this event.
492✔
1475
                // The hodl htlc must be present in the map.
492✔
1476
                circuitKey := htlcResolution.CircuitKey()
492✔
1477
                hodlHtlc, ok := l.hodlMap[circuitKey]
492✔
1478
                if !ok {
492✔
1479
                        return fmt.Errorf("hodl htlc not found: %v", circuitKey)
×
1480
                }
×
1481

1482
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
492✔
UNCOV
1483
                        return err
×
UNCOV
1484
                }
×
1485

1486
                // Clean up hodl map.
1487
                delete(l.hodlMap, circuitKey)
492✔
1488

492✔
1489
                select {
492✔
1490
                case item := <-l.hodlQueue.ChanOut():
4✔
1491
                        htlcResolution = item.(invoices.HtlcResolution)
4✔
1492
                default:
492✔
1493
                        break loop
492✔
1494
                }
1495
        }
1496

1497
        // Update the commitment tx.
1498
        if err := l.updateCommitTx(); err != nil {
493✔
1499
                return err
1✔
1500
        }
1✔
1501

1502
        return nil
491✔
1503
}
1504

1505
// processHtlcResolution applies a received htlc resolution to the provided
1506
// htlc. When this function returns without an error, the commit tx should be
1507
// updated.
1508
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1509
        htlc hodlHtlc) error {
638✔
1510

638✔
1511
        circuitKey := resolution.CircuitKey()
638✔
1512

638✔
1513
        // Determine required action for the resolution based on the type of
638✔
1514
        // resolution we have received.
638✔
1515
        switch res := resolution.(type) {
638✔
1516
        // Settle htlcs that returned a settle resolution using the preimage
1517
        // in the resolution.
1518
        case *invoices.HtlcSettleResolution:
634✔
1519
                l.log.Debugf("received settle resolution for %v "+
634✔
1520
                        "with outcome: %v", circuitKey, res.Outcome)
634✔
1521

634✔
1522
                return l.settleHTLC(res.Preimage, htlc.pd)
634✔
1523

1524
        // For htlc failures, we get the relevant failure message based
1525
        // on the failure resolution and then fail the htlc.
1526
        case *invoices.HtlcFailResolution:
8✔
1527
                l.log.Debugf("received cancel resolution for "+
8✔
1528
                        "%v with outcome: %v", circuitKey, res.Outcome)
8✔
1529

8✔
1530
                // Get the lnwire failure message based on the resolution
8✔
1531
                // result.
8✔
1532
                failure := getResolutionFailure(res, htlc.pd.Amount)
8✔
1533

8✔
1534
                l.sendHTLCError(
8✔
1535
                        htlc.pd, failure, htlc.obfuscator, true,
8✔
1536
                )
8✔
1537
                return nil
8✔
1538

1539
        // Fail if we do not get a settle of fail resolution, since we
1540
        // are only expecting to handle settles and fails.
UNCOV
1541
        default:
×
UNCOV
1542
                return fmt.Errorf("unknown htlc resolution type: %T",
×
UNCOV
1543
                        resolution)
×
1544
        }
1545
}
1546

1547
// getResolutionFailure returns the wire message that a htlc resolution should
1548
// be failed with.
1549
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1550
        amount lnwire.MilliSatoshi) *LinkError {
8✔
1551

8✔
1552
        // If the resolution has been resolved as part of a MPP timeout,
8✔
1553
        // we need to fail the htlc with lnwire.FailMppTimeout.
8✔
1554
        if resolution.Outcome == invoices.ResultMppTimeout {
8✔
UNCOV
1555
                return NewDetailedLinkError(
×
UNCOV
1556
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
UNCOV
1557
                )
×
UNCOV
1558
        }
×
1559

1560
        // If the htlc is not a MPP timeout, we fail it with
1561
        // FailIncorrectDetails. This error is sent for invoice payment
1562
        // failures such as underpayment/ expiry too soon and hodl invoices
1563
        // (which return FailIncorrectDetails to avoid leaking information).
1564
        incorrectDetails := lnwire.NewFailIncorrectDetails(
8✔
1565
                amount, uint32(resolution.AcceptHeight),
8✔
1566
        )
8✔
1567

8✔
1568
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
8✔
1569
}
1570

1571
// randomFeeUpdateTimeout returns a random timeout between the bounds defined
1572
// within the link's configuration that will be used to determine when the link
1573
// should propose an update to its commitment fee rate.
1574
func (l *channelLink) randomFeeUpdateTimeout() time.Duration {
219✔
1575
        lower := int64(l.cfg.MinUpdateTimeout)
219✔
1576
        upper := int64(l.cfg.MaxUpdateTimeout)
219✔
1577
        return time.Duration(prand.Int63n(upper-lower) + lower)
219✔
1578
}
219✔
1579

1580
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1581
// downstream HTLC Switch.
1582
func (l *channelLink) handleDownstreamUpdateAdd(pkt *htlcPacket) error {
1,524✔
1583
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
1,524✔
1584
        if !ok {
1,524✔
UNCOV
1585
                return errors.New("not an UpdateAddHTLC packet")
×
UNCOV
1586
        }
×
1587

1588
        // If we are flushing the link in the outgoing direction we can't add
1589
        // new htlcs to the link and we need to bounce it
1590
        if l.IsFlushing(Outgoing) {
1,524✔
1591
                l.mailBox.FailAdd(pkt)
×
1592

×
1593
                return NewDetailedLinkError(
×
UNCOV
1594
                        &lnwire.FailPermanentChannelFailure{},
×
UNCOV
1595
                        OutgoingFailureLinkNotEligible,
×
UNCOV
1596
                )
×
UNCOV
1597
        }
×
1598

1599
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1600
        // arbitrary delays between the switch adding an ADD to the
1601
        // mailbox, and the HTLC being added to the commitment state.
1602
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
1,524✔
UNCOV
1603
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
UNCOV
1604
                l.mailBox.AckPacket(pkt.inKey())
×
UNCOV
1605
                return nil
×
UNCOV
1606
        }
×
1607

1608
        // Check if we can add the HTLC here without exceededing the max fee
1609
        // exposure threshold.
1610
        if l.isOverexposedWithHtlc(htlc, false) {
1,528✔
1611
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1612
                        "exposure exceeded")
4✔
1613

4✔
1614
                l.mailBox.FailAdd(pkt)
4✔
1615

4✔
1616
                return NewDetailedLinkError(
4✔
1617
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1618
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1619
                )
4✔
1620
        }
4✔
1621

1622
        // A new payment has been initiated via the downstream channel,
1623
        // so we add the new HTLC to our local log, then update the
1624
        // commitment chains.
1625
        htlc.ChanID = l.ChanID()
1,520✔
1626
        openCircuitRef := pkt.inKey()
1,520✔
1627

1,520✔
1628
        // We enforce the fee buffer for the commitment transaction because
1,520✔
1629
        // we are in control of adding this htlc. Nothing has locked-in yet so
1,520✔
1630
        // we can securely enforce the fee buffer which is only relevant if we
1,520✔
1631
        // are the initiator of the channel.
1,520✔
1632
        index, err := l.channel.AddHTLC(htlc, &openCircuitRef)
1,520✔
1633
        if err != nil {
1,525✔
1634
                // The HTLC was unable to be added to the state machine,
5✔
1635
                // as a result, we'll signal the switch to cancel the
5✔
1636
                // pending payment.
5✔
1637
                l.log.Warnf("Unable to handle downstream add HTLC: %v",
5✔
1638
                        err)
5✔
1639

5✔
1640
                // Remove this packet from the link's mailbox, this
5✔
1641
                // prevents it from being reprocessed if the link
5✔
1642
                // restarts and resets it mailbox. If this response
5✔
1643
                // doesn't make it back to the originating link, it will
5✔
1644
                // be rejected upon attempting to reforward the Add to
5✔
1645
                // the switch, since the circuit was never fully opened,
5✔
1646
                // and the forwarding package shows it as
5✔
1647
                // unacknowledged.
5✔
1648
                l.mailBox.FailAdd(pkt)
5✔
1649

5✔
1650
                return NewDetailedLinkError(
5✔
1651
                        lnwire.NewTemporaryChannelFailure(nil),
5✔
1652
                        OutgoingFailureDownstreamHtlcAdd,
5✔
1653
                )
5✔
1654
        }
5✔
1655

1656
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
1,519✔
1657
                "local_log_index=%v, pend_updates=%v",
1,519✔
1658
                htlc.PaymentHash[:], index,
1,519✔
1659
                l.channel.PendingLocalUpdateCount())
1,519✔
1660

1,519✔
1661
        pkt.outgoingChanID = l.ShortChanID()
1,519✔
1662
        pkt.outgoingHTLCID = index
1,519✔
1663
        htlc.ID = index
1,519✔
1664

1,519✔
1665
        l.log.Debugf("queueing keystone of ADD open circuit: %s->%s",
1,519✔
1666
                pkt.inKey(), pkt.outKey())
1,519✔
1667

1,519✔
1668
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
1,519✔
1669
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
1,519✔
1670

1,519✔
1671
        _ = l.cfg.Peer.SendMessage(false, htlc)
1,519✔
1672

1,519✔
1673
        // Send a forward event notification to htlcNotifier.
1,519✔
1674
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
1,519✔
1675
                newHtlcKey(pkt),
1,519✔
1676
                HtlcInfo{
1,519✔
1677
                        IncomingTimeLock: pkt.incomingTimeout,
1,519✔
1678
                        IncomingAmt:      pkt.incomingAmount,
1,519✔
1679
                        OutgoingTimeLock: htlc.Expiry,
1,519✔
1680
                        OutgoingAmt:      htlc.Amount,
1,519✔
1681
                },
1,519✔
1682
                getEventType(pkt),
1,519✔
1683
        )
1,519✔
1684

1,519✔
1685
        l.tryBatchUpdateCommitTx()
1,519✔
1686

1,519✔
1687
        return nil
1,519✔
1688
}
1689

1690
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1691
// Switch. Possible messages sent by the switch include requests to forward new
1692
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1693
// cleared HTLCs with the upstream peer.
1694
//
1695
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1696
func (l *channelLink) handleDownstreamPkt(pkt *htlcPacket) {
1,565✔
1697
        switch htlc := pkt.htlc.(type) {
1,565✔
1698
        case *lnwire.UpdateAddHTLC:
1,524✔
1699
                // Handle add message. The returned error can be ignored,
1,524✔
1700
                // because it is also sent through the mailbox.
1,524✔
1701
                _ = l.handleDownstreamUpdateAdd(pkt)
1,524✔
1702

1703
        case *lnwire.UpdateFulfillHTLC:
27✔
1704
                // If hodl.SettleOutgoing mode is active, we exit early to
27✔
1705
                // simulate arbitrary delays between the switch adding the
27✔
1706
                // SETTLE to the mailbox, and the HTLC being added to the
27✔
1707
                // commitment state.
27✔
1708
                if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
27✔
UNCOV
1709
                        l.log.Warnf(hodl.SettleOutgoing.Warning())
×
UNCOV
1710
                        l.mailBox.AckPacket(pkt.inKey())
×
UNCOV
1711
                        return
×
UNCOV
1712
                }
×
1713

1714
                // An HTLC we forward to the switch has just settled somewhere
1715
                // upstream. Therefore we settle the HTLC within the our local
1716
                // state machine.
1717
                inKey := pkt.inKey()
27✔
1718
                err := l.channel.SettleHTLC(
27✔
1719
                        htlc.PaymentPreimage,
27✔
1720
                        pkt.incomingHTLCID,
27✔
1721
                        pkt.sourceRef,
27✔
1722
                        pkt.destRef,
27✔
1723
                        &inKey,
27✔
1724
                )
27✔
1725
                if err != nil {
27✔
1726
                        l.log.Errorf("unable to settle incoming HTLC for "+
×
1727
                                "circuit-key=%v: %v", inKey, err)
×
1728

×
1729
                        // If the HTLC index for Settle response was not known
×
1730
                        // to our commitment state, it has already been
×
1731
                        // cleaned up by a prior response. We'll thus try to
×
1732
                        // clean up any lingering state to ensure we don't
×
UNCOV
1733
                        // continue reforwarding.
×
UNCOV
1734
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
×
UNCOV
1735
                                l.cleanupSpuriousResponse(pkt)
×
1736
                        }
×
1737

1738
                        // Remove the packet from the link's mailbox to ensure
1739
                        // it doesn't get replayed after a reconnection.
UNCOV
1740
                        l.mailBox.AckPacket(inKey)
×
UNCOV
1741

×
UNCOV
1742
                        return
×
1743
                }
1744

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

27✔
1748
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
27✔
1749

27✔
1750
                // With the HTLC settled, we'll need to populate the wire
27✔
1751
                // message to target the specific channel and HTLC to be
27✔
1752
                // canceled.
27✔
1753
                htlc.ChanID = l.ChanID()
27✔
1754
                htlc.ID = pkt.incomingHTLCID
27✔
1755

27✔
1756
                // Then we send the HTLC settle message to the connected peer
27✔
1757
                // so we can continue the propagation of the settle message.
27✔
1758
                l.cfg.Peer.SendMessage(false, htlc)
27✔
1759

27✔
1760
                // Send a settle event notification to htlcNotifier.
27✔
1761
                l.cfg.HtlcNotifier.NotifySettleEvent(
27✔
1762
                        newHtlcKey(pkt),
27✔
1763
                        htlc.PaymentPreimage,
27✔
1764
                        getEventType(pkt),
27✔
1765
                )
27✔
1766

27✔
1767
                // Immediately update the commitment tx to minimize latency.
27✔
1768
                l.updateCommitTxOrFail()
27✔
1769

1770
        case *lnwire.UpdateFailHTLC:
22✔
1771
                // If hodl.FailOutgoing mode is active, we exit early to
22✔
1772
                // simulate arbitrary delays between the switch adding a FAIL to
22✔
1773
                // the mailbox, and the HTLC being added to the commitment
22✔
1774
                // state.
22✔
1775
                if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
22✔
UNCOV
1776
                        l.log.Warnf(hodl.FailOutgoing.Warning())
×
UNCOV
1777
                        l.mailBox.AckPacket(pkt.inKey())
×
UNCOV
1778
                        return
×
UNCOV
1779
                }
×
1780

1781
                // An HTLC cancellation has been triggered somewhere upstream,
1782
                // we'll remove then HTLC from our local state machine.
1783
                inKey := pkt.inKey()
22✔
1784
                err := l.channel.FailHTLC(
22✔
1785
                        pkt.incomingHTLCID,
22✔
1786
                        htlc.Reason,
22✔
1787
                        pkt.sourceRef,
22✔
1788
                        pkt.destRef,
22✔
1789
                        &inKey,
22✔
1790
                )
22✔
1791
                if err != nil {
28✔
1792
                        l.log.Errorf("unable to cancel incoming HTLC for "+
6✔
1793
                                "circuit-key=%v: %v", inKey, err)
6✔
1794

6✔
1795
                        // If the HTLC index for Fail response was not known to
6✔
1796
                        // our commitment state, it has already been cleaned up
6✔
1797
                        // by a prior response. We'll thus try to clean up any
6✔
1798
                        // lingering state to ensure we don't continue
6✔
1799
                        // reforwarding.
6✔
1800
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
8✔
1801
                                l.cleanupSpuriousResponse(pkt)
2✔
1802
                        }
2✔
1803

1804
                        // Remove the packet from the link's mailbox to ensure
1805
                        // it doesn't get replayed after a reconnection.
1806
                        l.mailBox.AckPacket(inKey)
6✔
1807

6✔
1808
                        return
6✔
1809
                }
1810

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

20✔
1814
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
20✔
1815

20✔
1816
                // With the HTLC removed, we'll need to populate the wire
20✔
1817
                // message to target the specific channel and HTLC to be
20✔
1818
                // canceled. The "Reason" field will have already been set
20✔
1819
                // within the switch.
20✔
1820
                htlc.ChanID = l.ChanID()
20✔
1821
                htlc.ID = pkt.incomingHTLCID
20✔
1822

20✔
1823
                // We send the HTLC message to the peer which initially created
20✔
1824
                // the HTLC. If the incoming blinding point is non-nil, we
20✔
1825
                // know that we are a relaying node in a blinded path.
20✔
1826
                // Otherwise, we're either an introduction node or not part of
20✔
1827
                // a blinded path at all.
20✔
1828
                if err := l.sendIncomingHTLCFailureMsg(
20✔
1829
                        htlc.ID,
20✔
1830
                        pkt.obfuscator,
20✔
1831
                        htlc.Reason,
20✔
1832
                ); err != nil {
20✔
1833
                        l.log.Errorf("unable to send HTLC failure: %v",
×
UNCOV
1834
                                err)
×
UNCOV
1835

×
UNCOV
1836
                        return
×
UNCOV
1837
                }
×
1838

1839
                // If the packet does not have a link failure set, it failed
1840
                // further down the route so we notify a forwarding failure.
1841
                // Otherwise, we notify a link failure because it failed at our
1842
                // node.
1843
                if pkt.linkFailure != nil {
34✔
1844
                        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
14✔
1845
                                newHtlcKey(pkt),
14✔
1846
                                newHtlcInfo(pkt),
14✔
1847
                                getEventType(pkt),
14✔
1848
                                pkt.linkFailure,
14✔
1849
                                false,
14✔
1850
                        )
14✔
1851
                } else {
24✔
1852
                        l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
10✔
1853
                                newHtlcKey(pkt), getEventType(pkt),
10✔
1854
                        )
10✔
1855
                }
10✔
1856

1857
                // Immediately update the commitment tx to minimize latency.
1858
                l.updateCommitTxOrFail()
20✔
1859
        }
1860
}
1861

1862
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1863
// full.
1864
func (l *channelLink) tryBatchUpdateCommitTx() {
1,519✔
1865
        if l.channel.PendingLocalUpdateCount() < uint64(l.cfg.BatchSize) {
2,487✔
1866
                return
968✔
1867
        }
968✔
1868

1869
        l.updateCommitTxOrFail()
555✔
1870
}
1871

1872
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1873
// associated with this packet. If successful in doing so, it will also purge
1874
// the open circuit from the circuit map and remove the packet from the link's
1875
// mailbox.
1876
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
2✔
1877
        inKey := pkt.inKey()
2✔
1878

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

2✔
1882
        // If the htlc packet doesn't have a source reference, it is unsafe to
2✔
1883
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
2✔
1884
        if pkt.sourceRef == nil {
3✔
1885
                l.log.Errorf("unable to cleanup response for incoming "+
1✔
1886
                        "circuit-key=%v, does not contain source reference",
1✔
1887
                        inKey)
1✔
1888
                return
1✔
1889
        }
1✔
1890

1891
        // If the source reference is present,  we will try to prevent this link
1892
        // from resending the packet to the switch. To do so, we ack the AddRef
1893
        // of the incoming HTLC belonging to this link.
1894
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
1✔
1895
        if err != nil {
1✔
1896
                l.log.Errorf("unable to ack AddRef for incoming "+
×
1897
                        "circuit-key=%v: %v", inKey, err)
×
1898

×
1899
                // If this operation failed, it is unsafe to attempt removal of
×
1900
                // the destination reference or circuit, so we exit early. The
×
UNCOV
1901
                // cleanup may proceed with a different packet in the future
×
UNCOV
1902
                // that succeeds on this step.
×
UNCOV
1903
                return
×
UNCOV
1904
        }
×
1905

1906
        // Now that we know this link will stop retransmitting Adds to the
1907
        // switch, we can begin to teardown the response reference and circuit
1908
        // map.
1909
        //
1910
        // If the packet includes a destination reference, then a response for
1911
        // this HTLC was locked into the outgoing channel. Attempt to remove
1912
        // this reference, so we stop retransmitting the response internally.
1913
        // Even if this fails, we will proceed in trying to delete the circuit.
1914
        // When retransmitting responses, the destination references will be
1915
        // cleaned up if an open circuit is not found in the circuit map.
1916
        if pkt.destRef != nil {
1✔
1917
                err := l.channel.AckSettleFails(*pkt.destRef)
×
1918
                if err != nil {
×
UNCOV
1919
                        l.log.Errorf("unable to ack SettleFailRef "+
×
UNCOV
1920
                                "for incoming circuit-key=%v: %v",
×
UNCOV
1921
                                inKey, err)
×
UNCOV
1922
                }
×
1923
        }
1924

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

1✔
1927
        // With all known references acked, we can now safely delete the circuit
1✔
1928
        // from the switch's circuit map, as the state is no longer needed.
1✔
1929
        err = l.cfg.Circuits.DeleteCircuits(inKey)
1✔
1930
        if err != nil {
1✔
UNCOV
1931
                l.log.Errorf("unable to delete circuit for "+
×
UNCOV
1932
                        "circuit-key=%v: %v", inKey, err)
×
UNCOV
1933
        }
×
1934
}
1935

1936
// handleUpstreamMsg processes wire messages related to commitment state
1937
// updates from the upstream peer. The upstream peer is the peer whom we have a
1938
// direct channel with, updating our respective commitment chains.
1939
func (l *channelLink) handleUpstreamMsg(msg lnwire.Message) {
6,948✔
1940
        switch msg := msg.(type) {
6,948✔
1941

1942
        case *lnwire.UpdateAddHTLC:
1,494✔
1943
                if l.IsFlushing(Incoming) {
1,494✔
1944
                        // This is forbidden by the protocol specification.
×
1945
                        // The best chance we have to deal with this is to drop
×
1946
                        // the connection. This should roll back the channel
×
1947
                        // state to the last CommitSig. If the remote has
×
1948
                        // already sent a CommitSig we haven't received yet,
×
1949
                        // channel state will be re-synchronized with a
×
1950
                        // ChannelReestablish message upon reconnection and the
×
1951
                        // protocol state that caused us to flush the link will
×
1952
                        // be rolled back. In the event that there was some
×
1953
                        // non-deterministic behavior in the remote that caused
×
1954
                        // them to violate the protocol, we have a decent shot
×
1955
                        // at correcting it this way, since reconnecting will
×
1956
                        // put us in the cleanest possible state to try again.
×
1957
                        //
×
1958
                        // In addition to the above, it is possible for us to
×
1959
                        // hit this case in situations where we improperly
×
1960
                        // handle message ordering due to concurrency choices.
×
1961
                        // An issue has been filed to address this here:
×
1962
                        // https://github.com/lightningnetwork/lnd/issues/8393
×
1963
                        l.fail(
×
1964
                                LinkFailureError{
×
1965
                                        code:             ErrInvalidUpdate,
×
1966
                                        FailureAction:    LinkFailureDisconnect,
×
1967
                                        PermanentFailure: false,
×
1968
                                        Warning:          true,
×
1969
                                },
×
1970
                                "received add while link is flushing",
×
UNCOV
1971
                        )
×
UNCOV
1972

×
UNCOV
1973
                        return
×
UNCOV
1974
                }
×
1975

1976
                // Disallow htlcs with blinding points set if we haven't
1977
                // enabled the feature. This saves us from having to process
1978
                // the onion at all, but will only catch blinded payments
1979
                // where we are a relaying node (as the blinding point will
1980
                // be in the payload when we're the introduction node).
1981
                if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
1,494✔
1982
                        l.fail(LinkFailureError{code: ErrInvalidUpdate},
×
1983
                                "blinding point included when route blinding "+
×
UNCOV
1984
                                        "is disabled")
×
UNCOV
1985

×
UNCOV
1986
                        return
×
UNCOV
1987
                }
×
1988

1989
                // We have to check the limit here rather than later in the
1990
                // switch because the counterparty can keep sending HTLC's
1991
                // without sending a revoke. This would mean that the switch
1992
                // check would only occur later.
1993
                if l.isOverexposedWithHtlc(msg, true) {
1,494✔
1994
                        l.fail(LinkFailureError{code: ErrInternalError},
×
1995
                                "peer sent us an HTLC that exceeded our max "+
×
UNCOV
1996
                                        "fee exposure")
×
UNCOV
1997

×
UNCOV
1998
                        return
×
UNCOV
1999
                }
×
2000

2001
                // We just received an add request from an upstream peer, so we
2002
                // add it to our state machine, then add the HTLC to our
2003
                // "settle" list in the event that we know the preimage.
2004
                index, err := l.channel.ReceiveHTLC(msg)
1,494✔
2005
                if err != nil {
1,494✔
UNCOV
2006
                        l.fail(LinkFailureError{code: ErrInvalidUpdate},
×
UNCOV
2007
                                "unable to handle upstream add HTLC: %v", err)
×
UNCOV
2008
                        return
×
UNCOV
2009
                }
×
2010

2011
                l.log.Tracef("receive upstream htlc with payment hash(%x), "+
1,494✔
2012
                        "assigning index: %v", msg.PaymentHash[:], index)
1,494✔
2013

2014
        case *lnwire.UpdateFulfillHTLC:
664✔
2015
                pre := msg.PaymentPreimage
664✔
2016
                idx := msg.ID
664✔
2017

664✔
2018
                // Before we pipeline the settle, we'll check the set of active
664✔
2019
                // htlc's to see if the related UpdateAddHTLC has been fully
664✔
2020
                // locked-in.
664✔
2021
                var lockedin bool
664✔
2022
                htlcs := l.channel.ActiveHtlcs()
664✔
2023
                for _, add := range htlcs {
62,013✔
2024
                        // The HTLC will be outgoing and match idx.
61,349✔
2025
                        if !add.Incoming && add.HtlcIndex == idx {
62,011✔
2026
                                lockedin = true
662✔
2027
                                break
662✔
2028
                        }
2029
                }
2030

2031
                if !lockedin {
666✔
2032
                        l.fail(
2✔
2033
                                LinkFailureError{code: ErrInvalidUpdate},
2✔
2034
                                "unable to handle upstream settle",
2✔
2035
                        )
2✔
2036
                        return
2✔
2037
                }
2✔
2038

2039
                if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
666✔
2040
                        l.fail(
4✔
2041
                                LinkFailureError{
4✔
2042
                                        code:          ErrInvalidUpdate,
4✔
2043
                                        FailureAction: LinkFailureForceClose,
4✔
2044
                                },
4✔
2045
                                "unable to handle upstream settle HTLC: %v", err,
4✔
2046
                        )
4✔
2047
                        return
4✔
2048
                }
4✔
2049

2050
                settlePacket := &htlcPacket{
662✔
2051
                        outgoingChanID: l.ShortChanID(),
662✔
2052
                        outgoingHTLCID: idx,
662✔
2053
                        htlc: &lnwire.UpdateFulfillHTLC{
662✔
2054
                                PaymentPreimage: pre,
662✔
2055
                        },
662✔
2056
                }
662✔
2057

662✔
2058
                // Add the newly discovered preimage to our growing list of
662✔
2059
                // uncommitted preimage. These will be written to the witness
662✔
2060
                // cache just before accepting the next commitment signature
662✔
2061
                // from the remote peer.
662✔
2062
                l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
662✔
2063

662✔
2064
                // Pipeline this settle, send it to the switch.
662✔
2065
                go l.forwardBatch(false, settlePacket)
662✔
2066

2067
        case *lnwire.UpdateFailMalformedHTLC:
7✔
2068
                // Convert the failure type encoded within the HTLC fail
7✔
2069
                // message to the proper generic lnwire error code.
7✔
2070
                var failure lnwire.FailureMessage
7✔
2071
                switch msg.FailureCode {
7✔
2072
                case lnwire.CodeInvalidOnionVersion:
5✔
2073
                        failure = &lnwire.FailInvalidOnionVersion{
5✔
2074
                                OnionSHA256: msg.ShaOnionBlob,
5✔
2075
                        }
5✔
UNCOV
2076
                case lnwire.CodeInvalidOnionHmac:
×
2077
                        failure = &lnwire.FailInvalidOnionHmac{
×
2078
                                OnionSHA256: msg.ShaOnionBlob,
×
2079
                        }
×
2080

UNCOV
2081
                case lnwire.CodeInvalidOnionKey:
×
UNCOV
2082
                        failure = &lnwire.FailInvalidOnionKey{
×
UNCOV
2083
                                OnionSHA256: msg.ShaOnionBlob,
×
UNCOV
2084
                        }
×
2085

2086
                // Handle malformed errors that are part of a blinded route.
2087
                // This case is slightly different, because we expect every
2088
                // relaying node in the blinded portion of the route to send
2089
                // malformed errors. If we're also a relaying node, we're
2090
                // likely going to switch this error out anyway for our own
2091
                // malformed error, but we handle the case here for
2092
                // completeness.
2093
                case lnwire.CodeInvalidBlinding:
4✔
2094
                        failure = &lnwire.FailInvalidBlinding{
4✔
2095
                                OnionSHA256: msg.ShaOnionBlob,
4✔
2096
                        }
4✔
2097

2098
                default:
2✔
2099
                        l.log.Warnf("unexpected failure code received in "+
2✔
2100
                                "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
2101

2✔
2102
                        // We don't just pass back the error we received from
2✔
2103
                        // our successor. Otherwise we might report a failure
2✔
2104
                        // that penalizes us more than needed. If the onion that
2✔
2105
                        // we forwarded was correct, the node should have been
2✔
2106
                        // able to send back its own failure. The node did not
2✔
2107
                        // send back its own failure, so we assume there was a
2✔
2108
                        // problem with the onion and report that back. We reuse
2✔
2109
                        // the invalid onion key failure because there is no
2✔
2110
                        // specific error for this case.
2✔
2111
                        failure = &lnwire.FailInvalidOnionKey{
2✔
2112
                                OnionSHA256: msg.ShaOnionBlob,
2✔
2113
                        }
2✔
2114
                }
2115

2116
                // With the error parsed, we'll convert the into it's opaque
2117
                // form.
2118
                var b bytes.Buffer
7✔
2119
                if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
7✔
UNCOV
2120
                        l.log.Errorf("unable to encode malformed error: %v", err)
×
UNCOV
2121
                        return
×
UNCOV
2122
                }
×
2123

2124
                // If remote side have been unable to parse the onion blob we
2125
                // have sent to it, than we should transform the malformed HTLC
2126
                // message to the usual HTLC fail message.
2127
                err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
7✔
2128
                if err != nil {
7✔
UNCOV
2129
                        l.fail(LinkFailureError{code: ErrInvalidUpdate},
×
UNCOV
2130
                                "unable to handle upstream fail HTLC: %v", err)
×
UNCOV
2131
                        return
×
UNCOV
2132
                }
×
2133

2134
        case *lnwire.UpdateFailHTLC:
124✔
2135
                // Verify that the failure reason is at least 256 bytes plus
124✔
2136
                // overhead.
124✔
2137
                const minimumFailReasonLength = lnwire.FailureMessageLength +
124✔
2138
                        2 + 2 + 32
124✔
2139

124✔
2140
                if len(msg.Reason) < minimumFailReasonLength {
125✔
2141
                        // We've received a reason with a non-compliant length.
1✔
2142
                        // Older nodes happily relay back these failures that
1✔
2143
                        // may originate from a node further downstream.
1✔
2144
                        // Therefore we can't just fail the channel.
1✔
2145
                        //
1✔
2146
                        // We want to be compliant ourselves, so we also can't
1✔
2147
                        // pass back the reason unmodified. And we must make
1✔
2148
                        // sure that we don't hit the magic length check of 260
1✔
2149
                        // bytes in processRemoteSettleFails either.
1✔
2150
                        //
1✔
2151
                        // Because the reason is unreadable for the payer
1✔
2152
                        // anyway, we just replace it by a compliant-length
1✔
2153
                        // series of random bytes.
1✔
2154
                        msg.Reason = make([]byte, minimumFailReasonLength)
1✔
2155
                        _, err := crand.Read(msg.Reason[:])
1✔
2156
                        if err != nil {
1✔
UNCOV
2157
                                l.log.Errorf("Random generation error: %v", err)
×
UNCOV
2158

×
UNCOV
2159
                                return
×
UNCOV
2160
                        }
×
2161
                }
2162

2163
                // Add fail to the update log.
2164
                idx := msg.ID
124✔
2165
                err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
124✔
2166
                if err != nil {
124✔
UNCOV
2167
                        l.fail(LinkFailureError{code: ErrInvalidUpdate},
×
UNCOV
2168
                                "unable to handle upstream fail HTLC: %v", err)
×
UNCOV
2169
                        return
×
UNCOV
2170
                }
×
2171

2172
        case *lnwire.CommitSig:
2,343✔
2173
                // Since we may have learned new preimages for the first time,
2,343✔
2174
                // we'll add them to our preimage cache. By doing this, we
2,343✔
2175
                // ensure any contested contracts watched by any on-chain
2,343✔
2176
                // arbitrators can now sweep this HTLC on-chain. We delay
2,343✔
2177
                // committing the preimages until just before accepting the new
2,343✔
2178
                // remote commitment, as afterwards the peer won't resend the
2,343✔
2179
                // Settle messages on the next channel reestablishment. Doing so
2,343✔
2180
                // allows us to more effectively batch this operation, instead
2,343✔
2181
                // of doing a single write per preimage.
2,343✔
2182
                err := l.cfg.PreimageCache.AddPreimages(
2,343✔
2183
                        l.uncommittedPreimages...,
2,343✔
2184
                )
2,343✔
2185
                if err != nil {
2,343✔
2186
                        l.fail(
×
2187
                                LinkFailureError{code: ErrInternalError},
×
2188
                                "unable to add preimages=%v to cache: %v",
×
UNCOV
2189
                                l.uncommittedPreimages, err,
×
UNCOV
2190
                        )
×
UNCOV
2191
                        return
×
UNCOV
2192
                }
×
2193

2194
                // Instead of truncating the slice to conserve memory
2195
                // allocations, we simply set the uncommitted preimage slice to
2196
                // nil so that a new one will be initialized if any more
2197
                // witnesses are discovered. We do this because the maximum size
2198
                // that the slice can occupy is 15KB, and we want to ensure we
2199
                // release that memory back to the runtime.
2200
                l.uncommittedPreimages = nil
2,343✔
2201

2,343✔
2202
                // We just received a new updates to our local commitment
2,343✔
2203
                // chain, validate this new commitment, closing the link if
2,343✔
2204
                // invalid.
2,343✔
2205
                err = l.channel.ReceiveNewCommitment(&lnwallet.CommitSigs{
2,343✔
2206
                        CommitSig:  msg.CommitSig,
2,343✔
2207
                        HtlcSigs:   msg.HtlcSigs,
2,343✔
2208
                        PartialSig: msg.PartialSig,
2,343✔
2209
                })
2,343✔
2210
                if err != nil {
2,343✔
2211
                        // If we were unable to reconstruct their proposed
×
2212
                        // commitment, then we'll examine the type of error. If
×
2213
                        // it's an InvalidCommitSigError, then we'll send a
×
2214
                        // direct error.
×
2215
                        var sendData []byte
×
2216
                        switch err.(type) {
×
UNCOV
2217
                        case *lnwallet.InvalidCommitSigError:
×
2218
                                sendData = []byte(err.Error())
×
2219
                        case *lnwallet.InvalidHtlcSigError:
×
2220
                                sendData = []byte(err.Error())
×
2221
                        }
2222
                        l.fail(
×
2223
                                LinkFailureError{
×
2224
                                        code:          ErrInvalidCommitment,
×
2225
                                        FailureAction: LinkFailureForceClose,
×
2226
                                        SendData:      sendData,
×
2227
                                },
×
2228
                                "ChannelPoint(%v): unable to accept new "+
×
UNCOV
2229
                                        "commitment: %v",
×
UNCOV
2230
                                l.channel.ChannelPoint(), err,
×
UNCOV
2231
                        )
×
UNCOV
2232
                        return
×
2233
                }
2234

2235
                // As we've just accepted a new state, we'll now
2236
                // immediately send the remote peer a revocation for our prior
2237
                // state.
2238
                nextRevocation, currentHtlcs, finalHTLCs, err :=
2,343✔
2239
                        l.channel.RevokeCurrentCommitment()
2,343✔
2240
                if err != nil {
2,343✔
2241
                        l.log.Errorf("unable to revoke commitment: %v", err)
×
2242

×
2243
                        // We need to fail the channel in case revoking our
×
2244
                        // local commitment does not succeed. We might have
×
2245
                        // already advanced our channel state which would lead
×
2246
                        // us to proceed with an unclean state.
×
2247
                        //
×
2248
                        // NOTE: We do not trigger a force close because this
×
2249
                        // could resolve itself in case our db was just busy
×
2250
                        // not accepting new transactions.
×
2251
                        l.fail(
×
2252
                                LinkFailureError{
×
2253
                                        code:          ErrInternalError,
×
2254
                                        Warning:       true,
×
2255
                                        FailureAction: LinkFailureDisconnect,
×
2256
                                },
×
2257
                                "ChannelPoint(%v): unable to accept new "+
×
2258
                                        "commitment: %v",
×
UNCOV
2259
                                l.channel.ChannelPoint(), err,
×
UNCOV
2260
                        )
×
UNCOV
2261
                        return
×
UNCOV
2262
                }
×
2263

2264
                // As soon as we are ready to send our next revocation, we can
2265
                // invoke the incoming commit hooks.
2266
                l.RWMutex.Lock()
2,343✔
2267
                l.incomingCommitHooks.invoke()
2,343✔
2268
                l.RWMutex.Unlock()
2,343✔
2269

2,343✔
2270
                l.cfg.Peer.SendMessage(false, nextRevocation)
2,343✔
2271

2,343✔
2272
                // Notify the incoming htlcs of which the resolutions were
2,343✔
2273
                // locked in.
2,343✔
2274
                for id, settled := range finalHTLCs {
3,115✔
2275
                        l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
772✔
2276
                                models.CircuitKey{
772✔
2277
                                        ChanID: l.ShortChanID(),
772✔
2278
                                        HtlcID: id,
772✔
2279
                                },
772✔
2280
                                channeldb.FinalHtlcInfo{
772✔
2281
                                        Settled:  settled,
772✔
2282
                                        Offchain: true,
772✔
2283
                                },
772✔
2284
                        )
772✔
2285
                }
772✔
2286

2287
                // Since we just revoked our commitment, we may have a new set
2288
                // of HTLC's on our commitment, so we'll send them using our
2289
                // function closure NotifyContractUpdate.
2290
                newUpdate := &contractcourt.ContractUpdate{
2,343✔
2291
                        HtlcKey: contractcourt.LocalHtlcSet,
2,343✔
2292
                        Htlcs:   currentHtlcs,
2,343✔
2293
                }
2,343✔
2294
                err = l.cfg.NotifyContractUpdate(newUpdate)
2,343✔
2295
                if err != nil {
2,343✔
UNCOV
2296
                        l.log.Errorf("unable to notify contract update: %v",
×
UNCOV
2297
                                err)
×
UNCOV
2298
                        return
×
UNCOV
2299
                }
×
2300

2301
                select {
2,343✔
2302
                case <-l.quit:
2✔
2303
                        return
2✔
2304
                default:
2,341✔
2305
                }
2306

2307
                // If the remote party initiated the state transition,
2308
                // we'll reply with a signature to provide them with their
2309
                // version of the latest commitment. Otherwise, both commitment
2310
                // chains are fully synced from our PoV, then we don't need to
2311
                // reply with a signature as both sides already have a
2312
                // commitment with the latest accepted.
2313
                if l.channel.OweCommitment() {
3,642✔
2314
                        if !l.updateCommitTxOrFail() {
1,301✔
UNCOV
2315
                                return
×
UNCOV
2316
                        }
×
2317
                }
2318

2319
                // Now that we have finished processing the incoming CommitSig
2320
                // and sent out our RevokeAndAck, we invoke the flushHooks if
2321
                // the channel state is clean.
2322
                l.RWMutex.Lock()
2,341✔
2323
                if l.channel.IsChannelClean() {
2,568✔
2324
                        l.flushHooks.invoke()
227✔
2325
                }
227✔
2326
                l.RWMutex.Unlock()
2,341✔
2327

2328
        case *lnwire.RevokeAndAck:
2,332✔
2329
                // We've received a revocation from the remote chain, if valid,
2,332✔
2330
                // this moves the remote chain forward, and expands our
2,332✔
2331
                // revocation window.
2,332✔
2332

2,332✔
2333
                // We now process the message and advance our remote commit
2,332✔
2334
                // chain.
2,332✔
2335
                fwdPkg, adds, settleFails, remoteHTLCs, err := l.channel.
2,332✔
2336
                        ReceiveRevocation(msg)
2,332✔
2337
                if err != nil {
2,332✔
2338
                        // TODO(halseth): force close?
×
2339
                        l.fail(
×
2340
                                LinkFailureError{
×
2341
                                        code:          ErrInvalidRevocation,
×
2342
                                        FailureAction: LinkFailureDisconnect,
×
2343
                                },
×
UNCOV
2344
                                "unable to accept revocation: %v", err,
×
UNCOV
2345
                        )
×
UNCOV
2346
                        return
×
UNCOV
2347
                }
×
2348

2349
                // The remote party now has a new primary commitment, so we'll
2350
                // update the contract court to be aware of this new set (the
2351
                // prior old remote pending).
2352
                newUpdate := &contractcourt.ContractUpdate{
2,332✔
2353
                        HtlcKey: contractcourt.RemoteHtlcSet,
2,332✔
2354
                        Htlcs:   remoteHTLCs,
2,332✔
2355
                }
2,332✔
2356
                err = l.cfg.NotifyContractUpdate(newUpdate)
2,332✔
2357
                if err != nil {
2,332✔
UNCOV
2358
                        l.log.Errorf("unable to notify contract update: %v",
×
UNCOV
2359
                                err)
×
UNCOV
2360
                        return
×
UNCOV
2361
                }
×
2362

2363
                select {
2,332✔
2364
                case <-l.quit:
3✔
2365
                        return
3✔
2366
                default:
2,329✔
2367
                }
2368

2369
                // If we have a tower client for this channel type, we'll
2370
                // create a backup for the current state.
2371
                if l.cfg.TowerClient != nil {
2,333✔
2372
                        state := l.channel.State()
4✔
2373
                        chanID := l.ChanID()
4✔
2374

4✔
2375
                        err = l.cfg.TowerClient.BackupState(
4✔
2376
                                &chanID, state.RemoteCommitment.CommitHeight-1,
4✔
2377
                        )
4✔
2378
                        if err != nil {
4✔
2379
                                l.fail(LinkFailureError{code: ErrInternalError},
×
UNCOV
2380
                                        "unable to queue breach backup: %v",
×
UNCOV
2381
                                        err)
×
UNCOV
2382
                                return
×
UNCOV
2383
                        }
×
2384
                }
2385

2386
                l.processRemoteSettleFails(fwdPkg, settleFails)
2,329✔
2387
                l.processRemoteAdds(fwdPkg, adds)
2,329✔
2388

2,329✔
2389
                // If the link failed during processing the adds, we must
2,329✔
2390
                // return to ensure we won't attempted to update the state
2,329✔
2391
                // further.
2,329✔
2392
                if l.failed {
2,329✔
UNCOV
2393
                        return
×
UNCOV
2394
                }
×
2395

2396
                // The revocation window opened up. If there are pending local
2397
                // updates, try to update the commit tx. Pending updates could
2398
                // already have been present because of a previously failed
2399
                // update to the commit tx or freshly added in by
2400
                // processRemoteAdds. Also in case there are no local updates,
2401
                // but there are still remote updates that are not in the remote
2402
                // commit tx yet, send out an update.
2403
                if l.channel.OweCommitment() {
2,922✔
2404
                        if !l.updateCommitTxOrFail() {
597✔
2405
                                return
4✔
2406
                        }
4✔
2407
                }
2408

2409
                // Now that we have finished processing the RevokeAndAck, we
2410
                // can invoke the flushHooks if the channel state is clean.
2411
                l.RWMutex.Lock()
2,325✔
2412
                if l.channel.IsChannelClean() {
2,501✔
2413
                        l.flushHooks.invoke()
176✔
2414
                }
176✔
2415
                l.RWMutex.Unlock()
2,325✔
2416

2417
        case *lnwire.UpdateFee:
3✔
2418
                // Check and see if their proposed fee-rate would make us
3✔
2419
                // exceed the fee threshold.
3✔
2420
                fee := chainfee.SatPerKWeight(msg.FeePerKw)
3✔
2421

3✔
2422
                isDust, err := l.exceedsFeeExposureLimit(fee)
3✔
2423
                if err != nil {
3✔
2424
                        // This shouldn't typically happen. If it does, it
×
2425
                        // indicates something is wrong with our channel state.
×
2426
                        l.log.Errorf("Unable to determine if fee threshold " +
×
2427
                                "exceeded")
×
2428
                        l.fail(LinkFailureError{code: ErrInternalError},
×
UNCOV
2429
                                "error calculating fee exposure: %v", err)
×
UNCOV
2430

×
2431
                        return
×
2432
                }
×
2433

2434
                if isDust {
3✔
2435
                        // The proposed fee-rate makes us exceed the fee
×
2436
                        // threshold.
×
UNCOV
2437
                        l.fail(LinkFailureError{code: ErrInternalError},
×
UNCOV
2438
                                "fee threshold exceeded: %v", err)
×
UNCOV
2439
                        return
×
UNCOV
2440
                }
×
2441

2442
                // We received fee update from peer. If we are the initiator we
2443
                // will fail the channel, if not we will apply the update.
2444
                if err := l.channel.ReceiveUpdateFee(fee); err != nil {
3✔
UNCOV
2445
                        l.fail(LinkFailureError{code: ErrInvalidUpdate},
×
UNCOV
2446
                                "error receiving fee update: %v", err)
×
UNCOV
2447
                        return
×
UNCOV
2448
                }
×
2449

2450
                // Update the mailbox's feerate as well.
2451
                l.mailBox.SetFeeRate(fee)
3✔
2452

2453
        // In the case where we receive a warning message from our peer, just
2454
        // log it and move on. We choose not to disconnect from our peer,
2455
        // although we "MAY" do so according to the specification.
2456
        case *lnwire.Warning:
1✔
2457
                l.log.Warnf("received warning message from peer: %v",
1✔
2458
                        msg.Warning())
1✔
2459

2460
        case *lnwire.Error:
3✔
2461
                // Error received from remote, MUST fail channel, but should
3✔
2462
                // only print the contents of the error message if all
3✔
2463
                // characters are printable ASCII.
3✔
2464
                l.fail(
3✔
2465
                        LinkFailureError{
3✔
2466
                                code: ErrRemoteError,
3✔
2467

3✔
2468
                                // TODO(halseth): we currently don't fail the
3✔
2469
                                // channel permanently, as there are some sync
3✔
2470
                                // issues with other implementations that will
3✔
2471
                                // lead to them sending an error message, but
3✔
2472
                                // we can recover from on next connection. See
3✔
2473
                                // https://github.com/ElementsProject/lightning/issues/4212
3✔
2474
                                PermanentFailure: false,
3✔
2475
                        },
3✔
2476
                        "ChannelPoint(%v): received error from peer: %v",
3✔
2477
                        l.channel.ChannelPoint(), msg.Error(),
3✔
2478
                )
3✔
UNCOV
2479
        default:
×
UNCOV
2480
                l.log.Warnf("received unknown message of type %T", msg)
×
2481
        }
2482

2483
}
2484

2485
// ackDownStreamPackets is responsible for removing htlcs from a link's mailbox
2486
// for packets delivered from server, and cleaning up any circuits closed by
2487
// signing a previous commitment txn. This method ensures that the circuits are
2488
// removed from the circuit map before removing them from the link's mailbox,
2489
// otherwise it could be possible for some circuit to be missed if this link
2490
// flaps.
2491
func (l *channelLink) ackDownStreamPackets() error {
2,516✔
2492
        // First, remove the downstream Add packets that were included in the
2,516✔
2493
        // previous commitment signature. This will prevent the Adds from being
2,516✔
2494
        // replayed if this link disconnects.
2,516✔
2495
        for _, inKey := range l.openedCircuits {
4,024✔
2496
                // In order to test the sphinx replay logic of the remote
1,508✔
2497
                // party, unsafe replay does not acknowledge the packets from
1,508✔
2498
                // the mailbox. We can then force a replay of any Add packets
1,508✔
2499
                // held in memory by disconnecting and reconnecting the link.
1,508✔
2500
                if l.cfg.UnsafeReplay {
1,512✔
2501
                        continue
4✔
2502
                }
2503

2504
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
1,508✔
2505
                l.mailBox.AckPacket(inKey)
1,508✔
2506
        }
2507

2508
        // Now, we will delete all circuits closed by the previous commitment
2509
        // signature, which is the result of downstream Settle/Fail packets. We
2510
        // batch them here to ensure circuits are closed atomically and for
2511
        // performance.
2512
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
2,516✔
2513
        switch err {
2,516✔
2514
        case nil:
2,516✔
2515
                // Successful deletion.
2516

UNCOV
2517
        default:
×
UNCOV
2518
                l.log.Errorf("unable to delete %d circuits: %v",
×
UNCOV
2519
                        len(l.closedCircuits), err)
×
UNCOV
2520
                return err
×
2521
        }
2522

2523
        // With the circuits removed from memory and disk, we now ack any
2524
        // Settle/Fails in the mailbox to ensure they do not get redelivered
2525
        // after startup. If forgive is enabled and we've reached this point,
2526
        // the circuits must have been removed at some point, so it is now safe
2527
        // to un-queue the corresponding Settle/Fails.
2528
        for _, inKey := range l.closedCircuits {
2,559✔
2529
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
43✔
2530
                        inKey)
43✔
2531
                l.mailBox.AckPacket(inKey)
43✔
2532
        }
43✔
2533

2534
        // Lastly, reset our buffers to be empty while keeping any acquired
2535
        // growth in the backing array.
2536
        l.openedCircuits = l.openedCircuits[:0]
2,516✔
2537
        l.closedCircuits = l.closedCircuits[:0]
2,516✔
2538

2,516✔
2539
        return nil
2,516✔
2540
}
2541

2542
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
2543
// the link.
2544
func (l *channelLink) updateCommitTxOrFail() bool {
2,741✔
2545
        err := l.updateCommitTx()
2,741✔
2546
        switch err {
2,741✔
2547
        // No error encountered, success.
2548
        case nil:
2,735✔
2549

2550
        // A duplicate keystone error should be resolved and is not fatal, so
2551
        // we won't send an Error message to the peer.
UNCOV
2552
        case ErrDuplicateKeystone:
×
UNCOV
2553
                l.fail(LinkFailureError{code: ErrCircuitError},
×
UNCOV
2554
                        "temporary circuit error: %v", err)
×
UNCOV
2555
                return false
×
2556

2557
        // Any other error is treated results in an Error message being sent to
2558
        // the peer.
2559
        default:
6✔
2560
                l.fail(LinkFailureError{code: ErrInternalError},
6✔
2561
                        "unable to update commitment: %v", err)
6✔
2562
                return false
6✔
2563
        }
2564

2565
        return true
2,735✔
2566
}
2567

2568
// updateCommitTx signs, then sends an update to the remote peer adding a new
2569
// commitment to their commitment chain which includes all the latest updates
2570
// we've received+processed up to this point.
2571
func (l *channelLink) updateCommitTx() error {
3,232✔
2572
        // Preemptively write all pending keystones to disk, just in case the
3,232✔
2573
        // HTLCs we have in memory are included in the subsequent attempt to
3,232✔
2574
        // sign a commitment state.
3,232✔
2575
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
3,232✔
2576
        if err != nil {
3,232✔
UNCOV
2577
                // If ErrDuplicateKeystone is returned, the caller will catch
×
UNCOV
2578
                // it.
×
UNCOV
2579
                return err
×
UNCOV
2580
        }
×
2581

2582
        // Reset the batch, but keep the backing buffer to avoid reallocating.
2583
        l.keystoneBatch = l.keystoneBatch[:0]
3,232✔
2584

3,232✔
2585
        // If hodl.Commit mode is active, we will refrain from attempting to
3,232✔
2586
        // commit any in-memory modifications to the channel state. Exiting here
3,232✔
2587
        // permits testing of either the switch or link's ability to trim
3,232✔
2588
        // circuits that have been opened, but unsuccessfully committed.
3,232✔
2589
        if l.cfg.HodlMask.Active(hodl.Commit) {
3,240✔
2590
                l.log.Warnf(hodl.Commit.Warning())
8✔
2591
                return nil
8✔
2592
        }
8✔
2593

2594
        newCommit, err := l.channel.SignNextCommitment()
3,228✔
2595
        if err == lnwallet.ErrNoWindow {
4,112✔
2596
                l.cfg.PendingCommitTicker.Resume()
884✔
2597
                l.log.Trace("PendingCommitTicker resumed")
884✔
2598

884✔
2599
                l.log.Tracef("revocation window exhausted, unable to send: "+
884✔
2600
                        "%v, pend_updates=%v, dangling_closes%v",
884✔
2601
                        l.channel.PendingLocalUpdateCount(),
884✔
2602
                        lnutils.SpewLogClosure(l.openedCircuits),
884✔
2603
                        lnutils.SpewLogClosure(l.closedCircuits))
884✔
2604

884✔
2605
                return nil
884✔
2606
        } else if err != nil {
3,232✔
2607
                return err
×
2608
        }
×
2609

2610
        if err := l.ackDownStreamPackets(); err != nil {
2,348✔
UNCOV
2611
                return err
×
UNCOV
2612
        }
×
2613

2614
        l.cfg.PendingCommitTicker.Pause()
2,348✔
2615
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
2,348✔
2616

2,348✔
2617
        // The remote party now has a new pending commitment, so we'll update
2,348✔
2618
        // the contract court to be aware of this new set (the prior old remote
2,348✔
2619
        // pending).
2,348✔
2620
        newUpdate := &contractcourt.ContractUpdate{
2,348✔
2621
                HtlcKey: contractcourt.RemotePendingHtlcSet,
2,348✔
2622
                Htlcs:   newCommit.PendingHTLCs,
2,348✔
2623
        }
2,348✔
2624
        err = l.cfg.NotifyContractUpdate(newUpdate)
2,348✔
2625
        if err != nil {
2,348✔
UNCOV
2626
                l.log.Errorf("unable to notify contract update: %v", err)
×
UNCOV
2627
                return err
×
UNCOV
2628
        }
×
2629

2630
        select {
2,348✔
2631
        case <-l.quit:
7✔
2632
                return ErrLinkShuttingDown
7✔
2633
        default:
2,341✔
2634
        }
2635

2636
        commitSig := &lnwire.CommitSig{
2,341✔
2637
                ChanID:     l.ChanID(),
2,341✔
2638
                CommitSig:  newCommit.CommitSig,
2,341✔
2639
                HtlcSigs:   newCommit.HtlcSigs,
2,341✔
2640
                PartialSig: newCommit.PartialSig,
2,341✔
2641
        }
2,341✔
2642
        l.cfg.Peer.SendMessage(false, commitSig)
2,341✔
2643

2,341✔
2644
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
2,341✔
2645
        // of commit hooks.
2,341✔
2646
        l.RWMutex.Lock()
2,341✔
2647
        l.outgoingCommitHooks.invoke()
2,341✔
2648
        l.RWMutex.Unlock()
2,341✔
2649

2,341✔
2650
        return nil
2,341✔
2651
}
2652

2653
// Peer returns the representation of remote peer with which we have the
2654
// channel link opened.
2655
//
2656
// NOTE: Part of the ChannelLink interface.
2657
func (l *channelLink) PeerPubKey() [33]byte {
441✔
2658
        return l.cfg.Peer.PubKey()
441✔
2659
}
441✔
2660

2661
// ChannelPoint returns the channel outpoint for the channel link.
2662
// NOTE: Part of the ChannelLink interface.
2663
func (l *channelLink) ChannelPoint() wire.OutPoint {
848✔
2664
        return l.channel.ChannelPoint()
848✔
2665
}
848✔
2666

2667
// ShortChanID returns the short channel ID for the channel link. The short
2668
// channel ID encodes the exact location in the main chain that the original
2669
// funding output can be found.
2670
//
2671
// NOTE: Part of the ChannelLink interface.
2672
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
9,492✔
2673
        l.RLock()
9,492✔
2674
        defer l.RUnlock()
9,492✔
2675

9,492✔
2676
        return l.channel.ShortChanID()
9,492✔
2677
}
9,492✔
2678

2679
// UpdateShortChanID updates the short channel ID for a link. This may be
2680
// required in the event that a link is created before the short chan ID for it
2681
// is known, or a re-org occurs, and the funding transaction changes location
2682
// within the chain.
2683
//
2684
// NOTE: Part of the ChannelLink interface.
2685
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
4✔
2686
        chanID := l.ChanID()
4✔
2687

4✔
2688
        // Refresh the channel state's short channel ID by loading it from disk.
4✔
2689
        // This ensures that the channel state accurately reflects the updated
4✔
2690
        // short channel ID.
4✔
2691
        err := l.channel.State().Refresh()
4✔
2692
        if err != nil {
4✔
UNCOV
2693
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
UNCOV
2694
                        "%v", chanID, err)
×
UNCOV
2695
                return hop.Source, err
×
UNCOV
2696
        }
×
2697

2698
        return hop.Source, nil
4✔
2699
}
2700

2701
// ChanID returns the channel ID for the channel link. The channel ID is a more
2702
// compact representation of a channel's full outpoint.
2703
//
2704
// NOTE: Part of the ChannelLink interface.
2705
func (l *channelLink) ChanID() lnwire.ChannelID {
7,142✔
2706
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
7,142✔
2707
}
7,142✔
2708

2709
// Bandwidth returns the total amount that can flow through the channel link at
2710
// this given instance. The value returned is expressed in millisatoshi and can
2711
// be used by callers when making forwarding decisions to determine if a link
2712
// can accept an HTLC.
2713
//
2714
// NOTE: Part of the ChannelLink interface.
2715
func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {
1,855✔
2716
        // Get the balance available on the channel for new HTLCs. This takes
1,855✔
2717
        // the channel reserve into account so HTLCs up to this value won't
1,855✔
2718
        // violate it.
1,855✔
2719
        return l.channel.AvailableBalance()
1,855✔
2720
}
1,855✔
2721

2722
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2723
// amount provided to the link. This check does not reserve a space, since
2724
// forwards or other payments may use the available slot, so it should be
2725
// considered best-effort.
2726
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
4✔
2727
        return l.channel.MayAddOutgoingHtlc(amt)
4✔
2728
}
4✔
2729

2730
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2731
// method.
2732
//
2733
// NOTE: Part of the dustHandler interface.
2734
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2735
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
7,903✔
2736

7,903✔
2737
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
7,903✔
2738
}
7,903✔
2739

2740
// getFeeRate is a wrapper method that retrieves the underlying channel's
2741
// feerate.
2742
//
2743
// NOTE: Part of the dustHandler interface.
2744
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
1,712✔
2745
        return l.channel.CommitFeeRate()
1,712✔
2746
}
1,712✔
2747

2748
// getDustClosure returns a closure that can be used by the switch or mailbox
2749
// to evaluate whether a given HTLC is dust.
2750
//
2751
// NOTE: Part of the dustHandler interface.
2752
func (l *channelLink) getDustClosure() dustClosure {
4,722✔
2753
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
4,722✔
2754
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
4,722✔
2755
        chanType := l.channel.State().ChanType
4,722✔
2756

4,722✔
2757
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
4,722✔
2758
}
4,722✔
2759

2760
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2761
// is used so that the Switch can have access to the commitment fee without
2762
// needing to have a *LightningChannel. This doesn't include dust.
2763
//
2764
// NOTE: Part of the dustHandler interface.
2765
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
6,417✔
2766
        if remote {
9,824✔
2767
                return l.channel.State().RemoteCommitment.CommitFee
3,407✔
2768
        }
3,407✔
2769

2770
        return l.channel.State().LocalCommitment.CommitFee
3,014✔
2771
}
2772

2773
// exceedsFeeExposureLimit returns whether or not the new proposed fee-rate
2774
// increases the total dust and fees within the channel past the configured
2775
// fee threshold. It first calculates the dust sum over every update in the
2776
// update log with the proposed fee-rate and taking into account both the local
2777
// and remote dust limits. It uses every update in the update log instead of
2778
// what is actually on the local and remote commitments because it is assumed
2779
// that in a worst-case scenario, every update in the update log could
2780
// theoretically be on either commitment transaction and this needs to be
2781
// accounted for with this fee-rate. It then calculates the local and remote
2782
// commitment fees given the proposed fee-rate. Finally, it tallies the results
2783
// and determines if the fee threshold has been exceeded.
2784
func (l *channelLink) exceedsFeeExposureLimit(
2785
        feePerKw chainfee.SatPerKWeight) (bool, error) {
6✔
2786

6✔
2787
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
6✔
2788

6✔
2789
        // Get the sum of dust for both the local and remote commitments using
6✔
2790
        // this "dry-run" fee.
6✔
2791
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
6✔
2792
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
6✔
2793

6✔
2794
        // Calculate the local and remote commitment fees using this dry-run
6✔
2795
        // fee.
6✔
2796
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
2797
        if err != nil {
6✔
UNCOV
2798
                return false, err
×
UNCOV
2799
        }
×
2800

2801
        // Finally, check whether the max fee exposure was exceeded on either
2802
        // future commitment transaction with the fee-rate.
2803
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
6✔
2804
        if totalLocalDust > l.cfg.MaxFeeExposure {
6✔
UNCOV
2805
                return true, nil
×
UNCOV
2806
        }
×
2807

2808
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
6✔
2809
                remoteFee,
6✔
2810
        )
6✔
2811

6✔
2812
        return totalRemoteDust > l.cfg.MaxFeeExposure, nil
6✔
2813
}
2814

2815
// isOverexposedWithHtlc calculates whether the proposed HTLC will make the
2816
// channel exceed the fee threshold. It first fetches the largest fee-rate that
2817
// may be on any unrevoked commitment transaction. Then, using this fee-rate,
2818
// determines if the to-be-added HTLC is dust. If the HTLC is dust, it adds to
2819
// the overall dust sum. If it is not dust, it contributes to weight, which
2820
// also adds to the overall dust sum by an increase in fees. If the dust sum on
2821
// either commitment exceeds the configured fee threshold, this function
2822
// returns true.
2823
func (l *channelLink) isOverexposedWithHtlc(htlc *lnwire.UpdateAddHTLC,
2824
        incoming bool) bool {
3,014✔
2825

3,014✔
2826
        dustClosure := l.getDustClosure()
3,014✔
2827

3,014✔
2828
        feeRate := l.channel.WorstCaseFeeRate()
3,014✔
2829

3,014✔
2830
        amount := htlc.Amount.ToSatoshis()
3,014✔
2831

3,014✔
2832
        // See if this HTLC is dust on both the local and remote commitments.
3,014✔
2833
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
3,014✔
2834
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
3,014✔
2835

3,014✔
2836
        // Calculate the dust sum for the local and remote commitments.
3,014✔
2837
        localDustSum := l.getDustSum(
3,014✔
2838
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
3,014✔
2839
        )
3,014✔
2840
        remoteDustSum := l.getDustSum(
3,014✔
2841
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
3,014✔
2842
        )
3,014✔
2843

3,014✔
2844
        // Grab the larger of the local and remote commitment fees w/o dust.
3,014✔
2845
        commitFee := l.getCommitFee(false)
3,014✔
2846

3,014✔
2847
        if l.getCommitFee(true) > commitFee {
3,410✔
2848
                commitFee = l.getCommitFee(true)
396✔
2849
        }
396✔
2850

2851
        localDustSum += lnwire.NewMSatFromSatoshis(commitFee)
3,014✔
2852
        remoteDustSum += lnwire.NewMSatFromSatoshis(commitFee)
3,014✔
2853

3,014✔
2854
        // Calculate the additional fee increase if this is a non-dust HTLC.
3,014✔
2855
        weight := lntypes.WeightUnit(input.HTLCWeight)
3,014✔
2856
        additional := lnwire.NewMSatFromSatoshis(
3,014✔
2857
                feeRate.FeeForWeight(weight),
3,014✔
2858
        )
3,014✔
2859

3,014✔
2860
        if isLocalDust {
4,867✔
2861
                // If this is dust, it doesn't contribute to weight but does
1,853✔
2862
                // contribute to the overall dust sum.
1,853✔
2863
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
1,853✔
2864
        } else {
3,018✔
2865
                // Account for the fee increase that comes with an increase in
1,165✔
2866
                // weight.
1,165✔
2867
                localDustSum += additional
1,165✔
2868
        }
1,165✔
2869

2870
        if localDustSum > l.cfg.MaxFeeExposure {
3,018✔
2871
                // The max fee exposure was exceeded.
4✔
2872
                return true
4✔
2873
        }
4✔
2874

2875
        if isRemoteDust {
4,860✔
2876
                // If this is dust, it doesn't contribute to weight but does
1,850✔
2877
                // contribute to the overall dust sum.
1,850✔
2878
                remoteDustSum += lnwire.NewMSatFromSatoshis(amount)
1,850✔
2879
        } else {
3,014✔
2880
                // Account for the fee increase that comes with an increase in
1,164✔
2881
                // weight.
1,164✔
2882
                remoteDustSum += additional
1,164✔
2883
        }
1,164✔
2884

2885
        return remoteDustSum > l.cfg.MaxFeeExposure
3,010✔
2886
}
2887

2888
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
2889
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
2890
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
2891
// whether to evaluate on the local or remote commit, and finally an HTLC
2892
// amount to test.
2893
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
2894
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
2895

2896
// dustHelper is used to construct the dustClosure.
2897
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
2898
        remoteDustLimit btcutil.Amount) dustClosure {
4,922✔
2899

4,922✔
2900
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
4,922✔
2901
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
51,640✔
2902

46,718✔
2903
                var dustLimit btcutil.Amount
46,718✔
2904
                if whoseCommit.IsLocal() {
70,079✔
2905
                        dustLimit = localDustLimit
23,361✔
2906
                } else {
46,722✔
2907
                        dustLimit = remoteDustLimit
23,361✔
2908
                }
23,361✔
2909

2910
                return lnwallet.HtlcIsDust(
46,718✔
2911
                        chantype, incoming, whoseCommit, feerate, amt,
46,718✔
2912
                        dustLimit,
46,718✔
2913
                )
46,718✔
2914
        }
2915

2916
        return isDust
4,922✔
2917
}
2918

2919
// zeroConfConfirmed returns whether or not the zero-conf channel has
2920
// confirmed on-chain.
2921
//
2922
// Part of the scidAliasHandler interface.
2923
func (l *channelLink) zeroConfConfirmed() bool {
7✔
2924
        return l.channel.State().ZeroConfConfirmed()
7✔
2925
}
7✔
2926

2927
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
2928
// should not be called for non-zero-conf channels.
2929
//
2930
// Part of the scidAliasHandler interface.
2931
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
7✔
2932
        return l.channel.State().ZeroConfRealScid()
7✔
2933
}
7✔
2934

2935
// isZeroConf returns whether or not the underlying channel is a zero-conf
2936
// channel.
2937
//
2938
// Part of the scidAliasHandler interface.
2939
func (l *channelLink) isZeroConf() bool {
215✔
2940
        return l.channel.State().IsZeroConf()
215✔
2941
}
215✔
2942

2943
// negotiatedAliasFeature returns whether or not the underlying channel has
2944
// negotiated the option-scid-alias feature bit. This will be true for both
2945
// option-scid-alias and zero-conf channel-types. It will also be true for
2946
// channels with the feature bit but without the above channel-types.
2947
//
2948
// Part of the scidAliasFeature interface.
2949
func (l *channelLink) negotiatedAliasFeature() bool {
374✔
2950
        return l.channel.State().NegotiatedAliasFeature()
374✔
2951
}
374✔
2952

2953
// getAliases returns the set of aliases for the underlying channel.
2954
//
2955
// Part of the scidAliasHandler interface.
2956
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
221✔
2957
        return l.cfg.GetAliases(l.ShortChanID())
221✔
2958
}
221✔
2959

2960
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
2961
//
2962
// Part of the scidAliasHandler interface.
2963
func (l *channelLink) attachFailAliasUpdate(closure func(
2964
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate) {
216✔
2965

216✔
2966
        l.Lock()
216✔
2967
        l.cfg.FailAliasUpdate = closure
216✔
2968
        l.Unlock()
216✔
2969
}
216✔
2970

2971
// AttachMailBox updates the current mailbox used by this link, and hooks up
2972
// the mailbox's message and packet outboxes to the link's upstream and
2973
// downstream chans, respectively.
2974
func (l *channelLink) AttachMailBox(mailbox MailBox) {
215✔
2975
        l.Lock()
215✔
2976
        l.mailBox = mailbox
215✔
2977
        l.upstream = mailbox.MessageOutBox()
215✔
2978
        l.downstream = mailbox.PacketOutBox()
215✔
2979
        l.Unlock()
215✔
2980

215✔
2981
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
215✔
2982
        // never committed.
215✔
2983
        l.mailBox.SetFeeRate(l.getFeeRate())
215✔
2984

215✔
2985
        // Also set the mailbox's dust closure so that it can query whether HTLC's
215✔
2986
        // are dust given the current feerate.
215✔
2987
        l.mailBox.SetDustClosure(l.getDustClosure())
215✔
2988
}
215✔
2989

2990
// UpdateForwardingPolicy updates the forwarding policy for the target
2991
// ChannelLink. Once updated, the link will use the new forwarding policy to
2992
// govern if it an incoming HTLC should be forwarded or not. We assume that
2993
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
2994
// update all of the link's FwrdingPolicy's values.
2995
//
2996
// NOTE: Part of the ChannelLink interface.
2997
func (l *channelLink) UpdateForwardingPolicy(
2998
        newPolicy models.ForwardingPolicy) {
16✔
2999

16✔
3000
        l.Lock()
16✔
3001
        defer l.Unlock()
16✔
3002

16✔
3003
        l.cfg.FwrdingPolicy = newPolicy
16✔
3004
}
16✔
3005

3006
// CheckHtlcForward should return a nil error if the passed HTLC details
3007
// satisfy the current forwarding policy fo the target link. Otherwise,
3008
// a LinkError with a valid protocol failure message should be returned
3009
// in order to signal to the source of the HTLC, the policy consistency
3010
// issue.
3011
//
3012
// NOTE: Part of the ChannelLink interface.
3013
func (l *channelLink) CheckHtlcForward(payHash [32]byte,
3014
        incomingHtlcAmt, amtToForward lnwire.MilliSatoshi,
3015
        incomingTimeout, outgoingTimeout uint32,
3016
        inboundFee models.InboundFee,
3017
        heightNow uint32, originalScid lnwire.ShortChannelID) *LinkError {
53✔
3018

53✔
3019
        l.RLock()
53✔
3020
        policy := l.cfg.FwrdingPolicy
53✔
3021
        l.RUnlock()
53✔
3022

53✔
3023
        // Using the outgoing HTLC amount, we'll calculate the outgoing
53✔
3024
        // fee this incoming HTLC must carry in order to satisfy the constraints
53✔
3025
        // of the outgoing link.
53✔
3026
        outFee := ExpectedFee(policy, amtToForward)
53✔
3027

53✔
3028
        // Then calculate the inbound fee that we charge based on the sum of
53✔
3029
        // outgoing HTLC amount and outgoing fee.
53✔
3030
        inFee := inboundFee.CalcFee(amtToForward + outFee)
53✔
3031

53✔
3032
        // Add up both fee components. It is important to calculate both fees
53✔
3033
        // separately. An alternative way of calculating is to first determine
53✔
3034
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
53✔
3035
        // rounding may cause the result to be slightly higher than in the case
53✔
3036
        // of separately rounded fee components. This potentially causes failed
53✔
3037
        // forwards for senders and is something to be avoided.
53✔
3038
        expectedFee := inFee + int64(outFee)
53✔
3039

53✔
3040
        // If the actual fee is less than our expected fee, then we'll reject
53✔
3041
        // this HTLC as it didn't provide a sufficient amount of fees, or the
53✔
3042
        // values have been tampered with, or the send used incorrect/dated
53✔
3043
        // information to construct the forwarding information for this hop. In
53✔
3044
        // any case, we'll cancel this HTLC.
53✔
3045
        actualFee := int64(incomingHtlcAmt) - int64(amtToForward)
53✔
3046
        if incomingHtlcAmt < amtToForward || actualFee < expectedFee {
63✔
3047
                l.log.Warnf("outgoing htlc(%x) has insufficient fee: "+
10✔
3048
                        "expected %v, got %v: incoming=%v, outgoing=%v, "+
10✔
3049
                        "inboundFee=%v",
10✔
3050
                        payHash[:], expectedFee, actualFee,
10✔
3051
                        incomingHtlcAmt, amtToForward, inboundFee,
10✔
3052
                )
10✔
3053

10✔
3054
                // As part of the returned error, we'll send our latest routing
10✔
3055
                // policy so the sending node obtains the most up to date data.
10✔
3056
                cb := func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
20✔
3057
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
10✔
3058
                }
10✔
3059
                failure := l.createFailureWithUpdate(false, originalScid, cb)
10✔
3060
                return NewLinkError(failure)
10✔
3061
        }
3062

3063
        // Check whether the outgoing htlc satisfies the channel policy.
3064
        err := l.canSendHtlc(
47✔
3065
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
47✔
3066
                originalScid,
47✔
3067
        )
47✔
3068
        if err != nil {
64✔
3069
                return err
17✔
3070
        }
17✔
3071

3072
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
3073
        // the following constraint: the incoming time-lock minus our time-lock
3074
        // delta should equal the outgoing time lock. Otherwise, whether the
3075
        // sender messed up, or an intermediate node tampered with the HTLC.
3076
        timeDelta := policy.TimeLockDelta
34✔
3077
        if incomingTimeout < outgoingTimeout+timeDelta {
36✔
3078
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
2✔
3079
                        "expected at least %v block delta, got %v block delta",
2✔
3080
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
2✔
3081

2✔
3082
                // Grab the latest routing policy so the sending node is up to
2✔
3083
                // date with our current policy.
2✔
3084
                cb := func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
4✔
3085
                        return lnwire.NewIncorrectCltvExpiry(
2✔
3086
                                incomingTimeout, *upd,
2✔
3087
                        )
2✔
3088
                }
2✔
3089
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3090
                return NewLinkError(failure)
2✔
3091
        }
3092

3093
        return nil
32✔
3094
}
3095

3096
// CheckHtlcTransit should return a nil error if the passed HTLC details
3097
// satisfy the current channel policy.  Otherwise, a LinkError with a
3098
// valid protocol failure message should be returned in order to signal
3099
// the violation. This call is intended to be used for locally initiated
3100
// payments for which there is no corresponding incoming htlc.
3101
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
3102
        amt lnwire.MilliSatoshi, timeout uint32,
3103
        heightNow uint32) *LinkError {
1,451✔
3104

1,451✔
3105
        l.RLock()
1,451✔
3106
        policy := l.cfg.FwrdingPolicy
1,451✔
3107
        l.RUnlock()
1,451✔
3108

1,451✔
3109
        // We pass in hop.Source here as this is only used in the Switch when
1,451✔
3110
        // trying to send over a local link. This causes the fallback mechanism
1,451✔
3111
        // to occur.
1,451✔
3112
        return l.canSendHtlc(
1,451✔
3113
                policy, payHash, amt, timeout, heightNow, hop.Source,
1,451✔
3114
        )
1,451✔
3115
}
1,451✔
3116

3117
// canSendHtlc checks whether the given htlc parameters satisfy
3118
// the channel's amount and time lock constraints.
3119
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
3120
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
3121
        heightNow uint32, originalScid lnwire.ShortChannelID) *LinkError {
1,494✔
3122

1,494✔
3123
        // As our first sanity check, we'll ensure that the passed HTLC isn't
1,494✔
3124
        // too small for the next hop. If so, then we'll cancel the HTLC
1,494✔
3125
        // directly.
1,494✔
3126
        if amt < policy.MinHTLCOut {
1,506✔
3127
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
12✔
3128
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
12✔
3129
                        amt)
12✔
3130

12✔
3131
                // As part of the returned error, we'll send our latest routing
12✔
3132
                // policy so the sending node obtains the most up to date data.
12✔
3133
                cb := func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
24✔
3134
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
12✔
3135
                }
12✔
3136
                failure := l.createFailureWithUpdate(false, originalScid, cb)
12✔
3137
                return NewLinkError(failure)
12✔
3138
        }
3139

3140
        // Next, ensure that the passed HTLC isn't too large. If so, we'll
3141
        // cancel the HTLC directly.
3142
        if policy.MaxHTLC != 0 && amt > policy.MaxHTLC {
1,493✔
3143
                l.log.Warnf("outgoing htlc(%x) is too large: max_htlc=%v, "+
7✔
3144
                        "htlc_value=%v", payHash[:], policy.MaxHTLC, amt)
7✔
3145

7✔
3146
                // As part of the returned error, we'll send our latest routing
7✔
3147
                // policy so the sending node obtains the most up-to-date data.
7✔
3148
                cb := func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
14✔
3149
                        return lnwire.NewTemporaryChannelFailure(upd)
7✔
3150
                }
7✔
3151
                failure := l.createFailureWithUpdate(false, originalScid, cb)
7✔
3152
                return NewDetailedLinkError(failure, OutgoingFailureHTLCExceedsMax)
7✔
3153
        }
3154

3155
        // We want to avoid offering an HTLC which will expire in the near
3156
        // future, so we'll reject an HTLC if the outgoing expiration time is
3157
        // too close to the current height.
3158
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
1,485✔
3159
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
2✔
3160
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
2✔
3161
                        timeout, heightNow)
2✔
3162

2✔
3163
                cb := func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
4✔
3164
                        return lnwire.NewExpiryTooSoon(*upd)
2✔
3165
                }
2✔
3166
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3167
                return NewLinkError(failure)
2✔
3168
        }
3169

3170
        // Check absolute max delta.
3171
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
1,482✔
3172
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
1✔
3173
                        "the future: got %v, but maximum is %v", payHash[:],
1✔
3174
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
1✔
3175

1✔
3176
                return NewLinkError(&lnwire.FailExpiryTooFar{})
1✔
3177
        }
1✔
3178

3179
        // Check to see if there is enough balance in this channel.
3180
        if amt > l.Bandwidth() {
1,485✔
3181
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
5✔
3182
                        "larger than %v", amt, l.Bandwidth())
5✔
3183
                cb := func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
10✔
3184
                        return lnwire.NewTemporaryChannelFailure(upd)
5✔
3185
                }
5✔
3186
                failure := l.createFailureWithUpdate(false, originalScid, cb)
5✔
3187
                return NewDetailedLinkError(
5✔
3188
                        failure, OutgoingFailureInsufficientBalance,
5✔
3189
                )
5✔
3190
        }
3191

3192
        return nil
1,479✔
3193
}
3194

3195
// Stats returns the statistics of channel link.
3196
//
3197
// NOTE: Part of the ChannelLink interface.
3198
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
24✔
3199
        snapshot := l.channel.StateSnapshot()
24✔
3200

24✔
3201
        return snapshot.ChannelCommitment.CommitHeight,
24✔
3202
                snapshot.TotalMSatSent,
24✔
3203
                snapshot.TotalMSatReceived
24✔
3204
}
24✔
3205

3206
// String returns the string representation of channel link.
3207
//
3208
// NOTE: Part of the ChannelLink interface.
UNCOV
3209
func (l *channelLink) String() string {
×
UNCOV
3210
        return l.channel.ChannelPoint().String()
×
UNCOV
3211
}
×
3212

3213
// handleSwitchPacket handles the switch packets. This packets which might be
3214
// forwarded to us from another channel link in case the htlc update came from
3215
// another peer or if the update was created by user
3216
//
3217
// NOTE: Part of the packetHandler interface.
3218
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
1,523✔
3219
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
1,523✔
3220
                pkt.inKey(), pkt.outKey())
1,523✔
3221

1,523✔
3222
        return l.mailBox.AddPacket(pkt)
1,523✔
3223
}
1,523✔
3224

3225
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
3226
// to us from remote peer we have a channel with.
3227
//
3228
// NOTE: Part of the ChannelLink interface.
3229
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
7,116✔
3230
        select {
7,116✔
3231
        case <-l.quit:
×
UNCOV
3232
                // Return early if the link is already in the process of
×
UNCOV
3233
                // quitting. It doesn't make sense to hand the message to the
×
UNCOV
3234
                // mailbox here.
×
UNCOV
3235
                return
×
3236
        default:
7,116✔
3237
        }
3238

3239
        err := l.mailBox.AddMessage(message)
7,116✔
3240
        if err != nil {
7,116✔
UNCOV
3241
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
UNCOV
3242
        }
×
3243
}
3244

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

3✔
3250
        // We skip sending the UpdateFee message if the channel is not
3✔
3251
        // currently eligible to forward messages.
3✔
3252
        if !l.EligibleToUpdate() {
3✔
UNCOV
3253
                l.log.Debugf("skipping fee update for inactive channel")
×
UNCOV
3254
                return nil
×
UNCOV
3255
        }
×
3256

3257
        // Check and see if our proposed fee-rate would make us exceed the fee
3258
        // threshold.
3259
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
3✔
3260
        if err != nil {
3✔
UNCOV
3261
                // This shouldn't typically happen. If it does, it indicates
×
UNCOV
3262
                // something is wrong with our channel state.
×
3263
                return err
×
3264
        }
×
3265

3266
        if thresholdExceeded {
3✔
UNCOV
3267
                return fmt.Errorf("link fee threshold exceeded")
×
3268
        }
×
3269

3270
        // First, we'll update the local fee on our commitment.
3271
        if err := l.channel.UpdateFee(feePerKw); err != nil {
3✔
UNCOV
3272
                return err
×
UNCOV
3273
        }
×
3274

3275
        // The fee passed the channel's validation checks, so we update the
3276
        // mailbox feerate.
3277
        l.mailBox.SetFeeRate(feePerKw)
3✔
3278

3✔
3279
        // We'll then attempt to send a new UpdateFee message, and also lock it
3✔
3280
        // in immediately by triggering a commitment update.
3✔
3281
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
3✔
3282
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
3✔
UNCOV
3283
                return err
×
UNCOV
3284
        }
×
3285
        return l.updateCommitTx()
3✔
3286
}
3287

3288
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
3289
// after receiving a revocation from the remote party, and reprocesses them in
3290
// the context of the provided forwarding package. Any settles or fails that
3291
// have already been acknowledged in the forwarding package will not be sent to
3292
// the switch.
3293
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg,
3294
        settleFails []*lnwallet.PaymentDescriptor) {
2,329✔
3295

2,329✔
3296
        if len(settleFails) == 0 {
3,908✔
3297
                return
1,579✔
3298
        }
1,579✔
3299

3300
        l.log.Debugf("settle-fail-filter %v", fwdPkg.SettleFailFilter)
754✔
3301

754✔
3302
        var switchPackets []*htlcPacket
754✔
3303
        for i, pd := range settleFails {
1,508✔
3304
                // Skip any settles or fails that have already been
754✔
3305
                // acknowledged by the incoming link that originated the
754✔
3306
                // forwarded Add.
754✔
3307
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
754✔
UNCOV
3308
                        continue
×
3309
                }
3310

3311
                // TODO(roasbeef): rework log entries to a shared
3312
                // interface.
3313

3314
                switch pd.EntryType {
754✔
3315

3316
                // A settle for an HTLC we previously forwarded HTLC has been
3317
                // received. So we'll forward the HTLC to the switch which will
3318
                // handle propagating the settle to the prior hop.
3319
                case lnwallet.Settle:
631✔
3320
                        // If hodl.SettleIncoming is requested, we will not
631✔
3321
                        // forward the SETTLE to the switch and will not signal
631✔
3322
                        // a free slot on the commitment transaction.
631✔
3323
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
631✔
UNCOV
3324
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
UNCOV
3325
                                continue
×
3326
                        }
3327

3328
                        settlePacket := &htlcPacket{
631✔
3329
                                outgoingChanID: l.ShortChanID(),
631✔
3330
                                outgoingHTLCID: pd.ParentIndex,
631✔
3331
                                destRef:        pd.DestRef,
631✔
3332
                                htlc: &lnwire.UpdateFulfillHTLC{
631✔
3333
                                        PaymentPreimage: pd.RPreimage,
631✔
3334
                                },
631✔
3335
                        }
631✔
3336

631✔
3337
                        // Add the packet to the batch to be forwarded, and
631✔
3338
                        // notify the overflow queue that a spare spot has been
631✔
3339
                        // freed up within the commitment state.
631✔
3340
                        switchPackets = append(switchPackets, settlePacket)
631✔
3341

3342
                // A failureCode message for a previously forwarded HTLC has
3343
                // been received. As a result a new slot will be freed up in
3344
                // our commitment state, so we'll forward this to the switch so
3345
                // the backwards undo can continue.
3346
                case lnwallet.Fail:
127✔
3347
                        // If hodl.SettleIncoming is requested, we will not
127✔
3348
                        // forward the FAIL to the switch and will not signal a
127✔
3349
                        // free slot on the commitment transaction.
127✔
3350
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
127✔
UNCOV
3351
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
UNCOV
3352
                                continue
×
3353
                        }
3354

3355
                        // Fetch the reason the HTLC was canceled so we can
3356
                        // continue to propagate it. This failure originated
3357
                        // from another node, so the linkFailure field is not
3358
                        // set on the packet.
3359
                        failPacket := &htlcPacket{
127✔
3360
                                outgoingChanID: l.ShortChanID(),
127✔
3361
                                outgoingHTLCID: pd.ParentIndex,
127✔
3362
                                destRef:        pd.DestRef,
127✔
3363
                                htlc: &lnwire.UpdateFailHTLC{
127✔
3364
                                        Reason: lnwire.OpaqueReason(
127✔
3365
                                                pd.FailReason,
127✔
3366
                                        ),
127✔
3367
                                },
127✔
3368
                        }
127✔
3369

127✔
3370
                        l.log.Debugf("Failed to send %s", pd.Amount)
127✔
3371

127✔
3372
                        // If the failure message lacks an HMAC (but includes
127✔
3373
                        // the 4 bytes for encoding the message and padding
127✔
3374
                        // lengths, then this means that we received it as an
127✔
3375
                        // UpdateFailMalformedHTLC. As a result, we'll signal
127✔
3376
                        // that we need to convert this error within the switch
127✔
3377
                        // to an actual error, by encrypting it as if we were
127✔
3378
                        // the originating hop.
127✔
3379
                        convertedErrorSize := lnwire.FailureMessageLength + 4
127✔
3380
                        if len(pd.FailReason) == convertedErrorSize {
134✔
3381
                                failPacket.convertedError = true
7✔
3382
                        }
7✔
3383

3384
                        // Add the packet to the batch to be forwarded, and
3385
                        // notify the overflow queue that a spare spot has been
3386
                        // freed up within the commitment state.
3387
                        switchPackets = append(switchPackets, failPacket)
127✔
3388
                }
3389
        }
3390

3391
        // Only spawn the task forward packets we have a non-zero number.
3392
        if len(switchPackets) > 0 {
1,508✔
3393
                go l.forwardBatch(false, switchPackets...)
754✔
3394
        }
754✔
3395
}
3396

3397
// processRemoteAdds serially processes each of the Add payment descriptors
3398
// which have been "locked-in" by receiving a revocation from the remote party.
3399
// The forwarding package provided instructs how to process this batch,
3400
// indicating whether this is the first time these Adds are being processed, or
3401
// whether we are reprocessing as a result of a failure or restart. Adds that
3402
// have already been acknowledged in the forwarding package will be ignored.
3403
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg,
3404
        lockedInHtlcs []*lnwallet.PaymentDescriptor) {
2,332✔
3405

2,332✔
3406
        l.log.Tracef("processing %d remote adds for height %d",
2,332✔
3407
                len(lockedInHtlcs), fwdPkg.Height)
2,332✔
3408

2,332✔
3409
        decodeReqs := make(
2,332✔
3410
                []hop.DecodeHopIteratorRequest, 0, len(lockedInHtlcs),
2,332✔
3411
        )
2,332✔
3412
        for _, pd := range lockedInHtlcs {
3,826✔
3413
                switch pd.EntryType {
1,494✔
3414

3415
                // TODO(conner): remove type switch?
3416
                case lnwallet.Add:
1,494✔
3417
                        // Before adding the new htlc to the state machine,
1,494✔
3418
                        // parse the onion object in order to obtain the
1,494✔
3419
                        // routing information with DecodeHopIterator function
1,494✔
3420
                        // which process the Sphinx packet.
1,494✔
3421
                        onionReader := bytes.NewReader(pd.OnionBlob)
1,494✔
3422

1,494✔
3423
                        req := hop.DecodeHopIteratorRequest{
1,494✔
3424
                                OnionReader:    onionReader,
1,494✔
3425
                                RHash:          pd.RHash[:],
1,494✔
3426
                                IncomingCltv:   pd.Timeout,
1,494✔
3427
                                IncomingAmount: pd.Amount,
1,494✔
3428
                                BlindingPoint:  pd.BlindingPoint,
1,494✔
3429
                        }
1,494✔
3430

1,494✔
3431
                        decodeReqs = append(decodeReqs, req)
1,494✔
3432
                }
3433
        }
3434

3435
        // Atomically decode the incoming htlcs, simultaneously checking for
3436
        // replay attempts. A particular index in the returned, spare list of
3437
        // channel iterators should only be used if the failure code at the
3438
        // same index is lnwire.FailCodeNone.
3439
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
2,332✔
3440
                fwdPkg.ID(), decodeReqs,
2,332✔
3441
        )
2,332✔
3442
        if sphinxErr != nil {
2,332✔
UNCOV
3443
                l.fail(LinkFailureError{code: ErrInternalError},
×
UNCOV
3444
                        "unable to decode hop iterators: %v", sphinxErr)
×
UNCOV
3445
                return
×
UNCOV
3446
        }
×
3447

3448
        var switchPackets []*htlcPacket
2,332✔
3449

2,332✔
3450
        for i, pd := range lockedInHtlcs {
3,826✔
3451
                idx := uint16(i)
1,494✔
3452

1,494✔
3453
                if fwdPkg.State == channeldb.FwdStateProcessed &&
1,494✔
3454
                        fwdPkg.AckFilter.Contains(idx) {
1,494✔
3455

×
3456
                        // If this index is already found in the ack filter,
×
3457
                        // the response to this forwarding decision has already
×
UNCOV
3458
                        // been committed by one of our commitment txns. ADDs
×
UNCOV
3459
                        // in this state are waiting for the rest of the fwding
×
UNCOV
3460
                        // package to get acked before being garbage collected.
×
UNCOV
3461
                        continue
×
3462
                }
3463

3464
                // An incoming HTLC add has been full-locked in. As a result we
3465
                // can now examine the forwarding details of the HTLC, and the
3466
                // HTLC itself to decide if: we should forward it, cancel it,
3467
                // or are able to settle it (and it adheres to our fee related
3468
                // constraints).
3469

3470
                // Fetch the onion blob that was included within this processed
3471
                // payment descriptor.
3472
                var onionBlob [lnwire.OnionPacketSize]byte
1,494✔
3473
                copy(onionBlob[:], pd.OnionBlob)
1,494✔
3474

1,494✔
3475
                // Before adding the new htlc to the state machine, parse the
1,494✔
3476
                // onion object in order to obtain the routing information with
1,494✔
3477
                // DecodeHopIterator function which process the Sphinx packet.
1,494✔
3478
                chanIterator, failureCode := decodeResps[i].Result()
1,494✔
3479
                if failureCode != lnwire.CodeNone {
1,500✔
3480
                        // If we're unable to process the onion blob then we
6✔
3481
                        // should send the malformed htlc error to payment
6✔
3482
                        // sender.
6✔
3483
                        l.sendMalformedHTLCError(pd.HtlcIndex, failureCode,
6✔
3484
                                onionBlob[:], pd.SourceRef)
6✔
3485

6✔
3486
                        l.log.Errorf("unable to decode onion hop "+
6✔
3487
                                "iterator: %v", failureCode)
6✔
3488
                        continue
6✔
3489
                }
3490

3491
                heightNow := l.cfg.BestHeight()
1,492✔
3492

1,492✔
3493
                pld, routeRole, pldErr := chanIterator.HopPayload()
1,492✔
3494
                if pldErr != nil {
1,496✔
3495
                        // If we're unable to process the onion payload, or we
4✔
3496
                        // received invalid onion payload failure, then we
4✔
3497
                        // should send an error back to the caller so the HTLC
4✔
3498
                        // can be canceled.
4✔
3499
                        var failedType uint64
4✔
3500

4✔
3501
                        // We need to get the underlying error value, so we
4✔
3502
                        // can't use errors.As as suggested by the linter.
4✔
3503
                        //nolint:errorlint
4✔
3504
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
4✔
UNCOV
3505
                                failedType = uint64(e.Type)
×
UNCOV
3506
                        }
×
3507

3508
                        // If we couldn't parse the payload, make our best
3509
                        // effort at creating an error encrypter that knows
3510
                        // what blinding type we were, but if we couldn't
3511
                        // parse the payload we have no way of knowing whether
3512
                        // we were the introduction node or not.
3513
                        //
3514
                        //nolint:lll
3515
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
4✔
3516
                                l.cfg.ExtractErrorEncrypter,
4✔
3517
                                // We need our route role here because we
4✔
3518
                                // couldn't parse or validate the payload.
4✔
3519
                                routeRole == hop.RouteRoleIntroduction,
4✔
3520
                        )
4✔
3521
                        if failCode != lnwire.CodeNone {
4✔
3522
                                l.log.Errorf("could not extract error "+
×
3523
                                        "encrypter: %v", pldErr)
×
3524

×
3525
                                // We can't process this htlc, send back
×
3526
                                // malformed.
×
3527
                                l.sendMalformedHTLCError(
×
3528
                                        pd.HtlcIndex, failureCode,
×
UNCOV
3529
                                        onionBlob[:], pd.SourceRef,
×
UNCOV
3530
                                )
×
UNCOV
3531

×
UNCOV
3532
                                continue
×
3533
                        }
3534

3535
                        // TODO: currently none of the test unit infrastructure
3536
                        // is setup to handle TLV payloads, so testing this
3537
                        // would require implementing a separate mock iterator
3538
                        // for TLV payloads that also supports injecting invalid
3539
                        // payloads. Deferring this non-trival effort till a
3540
                        // later date
3541
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
4✔
3542
                        l.sendHTLCError(
4✔
3543
                                pd, NewLinkError(failure), obfuscator, false,
4✔
3544
                        )
4✔
3545

4✔
3546
                        l.log.Errorf("unable to decode forwarding "+
4✔
3547
                                "instructions: %v", pldErr)
4✔
3548

4✔
3549
                        continue
4✔
3550
                }
3551

3552
                // Retrieve onion obfuscator from onion blob in order to
3553
                // produce initial obfuscation of the onion failureCode.
3554
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
1,492✔
3555
                        l.cfg.ExtractErrorEncrypter,
1,492✔
3556
                        routeRole == hop.RouteRoleIntroduction,
1,492✔
3557
                )
1,492✔
3558
                if failureCode != lnwire.CodeNone {
1,493✔
3559
                        // If we're unable to process the onion blob than we
1✔
3560
                        // should send the malformed htlc error to payment
1✔
3561
                        // sender.
1✔
3562
                        l.sendMalformedHTLCError(
1✔
3563
                                pd.HtlcIndex, failureCode, onionBlob[:],
1✔
3564
                                pd.SourceRef,
1✔
3565
                        )
1✔
3566

1✔
3567
                        l.log.Errorf("unable to decode onion "+
1✔
3568
                                "obfuscator: %v", failureCode)
1✔
3569

1✔
3570
                        continue
1✔
3571
                }
3572

3573
                fwdInfo := pld.ForwardingInfo()
1,491✔
3574

1,491✔
3575
                // Check whether the payload we've just processed uses our
1,491✔
3576
                // node as the introduction point (gave us a blinding key in
1,491✔
3577
                // the payload itself) and fail it back if we don't support
1,491✔
3578
                // route blinding.
1,491✔
3579
                if fwdInfo.NextBlinding.IsSome() &&
1,491✔
3580
                        l.cfg.DisallowRouteBlinding {
1,495✔
3581

4✔
3582
                        failure := lnwire.NewInvalidBlinding(
4✔
3583
                                onionBlob[:],
4✔
3584
                        )
4✔
3585
                        l.sendHTLCError(
4✔
3586
                                pd, NewLinkError(failure), obfuscator, false,
4✔
3587
                        )
4✔
3588

4✔
3589
                        l.log.Error("rejected htlc that uses use as an " +
4✔
3590
                                "introduction point when we do not support " +
4✔
3591
                                "route blinding")
4✔
3592

4✔
3593
                        continue
4✔
3594
                }
3595

3596
                switch fwdInfo.NextHop {
1,491✔
3597
                case hop.Exit:
1,455✔
3598
                        err := l.processExitHop(
1,455✔
3599
                                pd, obfuscator, fwdInfo, heightNow, pld,
1,455✔
3600
                        )
1,455✔
3601
                        if err != nil {
1,455✔
3602
                                l.fail(LinkFailureError{code: ErrInternalError},
×
3603
                                        err.Error(),
×
UNCOV
3604
                                )
×
UNCOV
3605

×
UNCOV
3606
                                return
×
UNCOV
3607
                        }
×
3608

3609
                // There are additional channels left within this route. So
3610
                // we'll simply do some forwarding package book-keeping.
3611
                default:
40✔
3612
                        // If hodl.AddIncoming is requested, we will not
40✔
3613
                        // validate the forwarded ADD, nor will we send the
40✔
3614
                        // packet to the htlc switch.
40✔
3615
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
40✔
UNCOV
3616
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
UNCOV
3617
                                continue
×
3618
                        }
3619

3620
                        switch fwdPkg.State {
40✔
3621
                        case channeldb.FwdStateProcessed:
4✔
3622
                                // This add was not forwarded on the previous
4✔
3623
                                // processing phase, run it through our
4✔
3624
                                // validation pipeline to reproduce an error.
4✔
3625
                                // This may trigger a different error due to
4✔
3626
                                // expiring timelocks, but we expect that an
4✔
3627
                                // error will be reproduced.
4✔
3628
                                if !fwdPkg.FwdFilter.Contains(idx) {
4✔
UNCOV
3629
                                        break
×
3630
                                }
3631

3632
                                // Otherwise, it was already processed, we can
3633
                                // can collect it and continue.
3634
                                addMsg := &lnwire.UpdateAddHTLC{
4✔
3635
                                        Expiry:        fwdInfo.OutgoingCTLV,
4✔
3636
                                        Amount:        fwdInfo.AmountToForward,
4✔
3637
                                        PaymentHash:   pd.RHash,
4✔
3638
                                        BlindingPoint: fwdInfo.NextBlinding,
4✔
3639
                                }
4✔
3640

4✔
3641
                                // Finally, we'll encode the onion packet for
4✔
3642
                                // the _next_ hop using the hop iterator
4✔
3643
                                // decoded for the current hop.
4✔
3644
                                buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
4✔
3645

4✔
3646
                                // We know this cannot fail, as this ADD
4✔
3647
                                // was marked forwarded in a previous
4✔
3648
                                // round of processing.
4✔
3649
                                chanIterator.EncodeNextHop(buf)
4✔
3650

4✔
3651
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
4✔
3652

4✔
3653
                                updatePacket := &htlcPacket{
4✔
3654
                                        incomingChanID:  l.ShortChanID(),
4✔
3655
                                        incomingHTLCID:  pd.HtlcIndex,
4✔
3656
                                        outgoingChanID:  fwdInfo.NextHop,
4✔
3657
                                        sourceRef:       pd.SourceRef,
4✔
3658
                                        incomingAmount:  pd.Amount,
4✔
3659
                                        amount:          addMsg.Amount,
4✔
3660
                                        htlc:            addMsg,
4✔
3661
                                        obfuscator:      obfuscator,
4✔
3662
                                        incomingTimeout: pd.Timeout,
4✔
3663
                                        outgoingTimeout: fwdInfo.OutgoingCTLV,
4✔
3664
                                        customRecords:   pld.CustomRecords(),
4✔
3665
                                        inboundFee:      inboundFee,
4✔
3666
                                }
4✔
3667
                                switchPackets = append(
4✔
3668
                                        switchPackets, updatePacket,
4✔
3669
                                )
4✔
3670

4✔
3671
                                continue
4✔
3672
                        }
3673

3674
                        // TODO(roasbeef): ensure don't accept outrageous
3675
                        // timeout for htlc
3676

3677
                        // With all our forwarding constraints met, we'll
3678
                        // create the outgoing HTLC using the parameters as
3679
                        // specified in the forwarding info.
3680
                        addMsg := &lnwire.UpdateAddHTLC{
40✔
3681
                                Expiry:        fwdInfo.OutgoingCTLV,
40✔
3682
                                Amount:        fwdInfo.AmountToForward,
40✔
3683
                                PaymentHash:   pd.RHash,
40✔
3684
                                BlindingPoint: fwdInfo.NextBlinding,
40✔
3685
                        }
40✔
3686

40✔
3687
                        // Finally, we'll encode the onion packet for the
40✔
3688
                        // _next_ hop using the hop iterator decoded for the
40✔
3689
                        // current hop.
40✔
3690
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
40✔
3691
                        err := chanIterator.EncodeNextHop(buf)
40✔
3692
                        if err != nil {
40✔
3693
                                l.log.Errorf("unable to encode the "+
×
3694
                                        "remaining route %v", err)
×
UNCOV
3695

×
3696
                                cb := func(upd *lnwire.ChannelUpdate) lnwire.FailureMessage {
×
3697
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
3698
                                }
×
3699

3700
                                failure := l.createFailureWithUpdate(
×
3701
                                        true, hop.Source, cb,
×
3702
                                )
×
3703

×
UNCOV
3704
                                l.sendHTLCError(
×
UNCOV
3705
                                        pd, NewLinkError(failure), obfuscator, false,
×
UNCOV
3706
                                )
×
UNCOV
3707
                                continue
×
3708
                        }
3709

3710
                        // Now that this add has been reprocessed, only append
3711
                        // it to our list of packets to forward to the switch
3712
                        // this is the first time processing the add. If the
3713
                        // fwd pkg has already been processed, then we entered
3714
                        // the above section to recreate a previous error.  If
3715
                        // the packet had previously been forwarded, it would
3716
                        // have been added to switchPackets at the top of this
3717
                        // section.
3718
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
80✔
3719
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
40✔
3720

40✔
3721
                                updatePacket := &htlcPacket{
40✔
3722
                                        incomingChanID:  l.ShortChanID(),
40✔
3723
                                        incomingHTLCID:  pd.HtlcIndex,
40✔
3724
                                        outgoingChanID:  fwdInfo.NextHop,
40✔
3725
                                        sourceRef:       pd.SourceRef,
40✔
3726
                                        incomingAmount:  pd.Amount,
40✔
3727
                                        amount:          addMsg.Amount,
40✔
3728
                                        htlc:            addMsg,
40✔
3729
                                        obfuscator:      obfuscator,
40✔
3730
                                        incomingTimeout: pd.Timeout,
40✔
3731
                                        outgoingTimeout: fwdInfo.OutgoingCTLV,
40✔
3732
                                        customRecords:   pld.CustomRecords(),
40✔
3733
                                        inboundFee:      inboundFee,
40✔
3734
                                }
40✔
3735

40✔
3736
                                fwdPkg.FwdFilter.Set(idx)
40✔
3737
                                switchPackets = append(switchPackets,
40✔
3738
                                        updatePacket)
40✔
3739
                        }
40✔
3740
                }
3741
        }
3742

3743
        // Commit the htlcs we are intending to forward if this package has not
3744
        // been fully processed.
3745
        if fwdPkg.State == channeldb.FwdStateLockedIn {
4,661✔
3746
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
2,329✔
3747
                if err != nil {
2,329✔
UNCOV
3748
                        l.fail(LinkFailureError{code: ErrInternalError},
×
UNCOV
3749
                                "unable to set fwd filter: %v", err)
×
UNCOV
3750
                        return
×
UNCOV
3751
                }
×
3752
        }
3753

3754
        if len(switchPackets) == 0 {
4,628✔
3755
                return
2,296✔
3756
        }
2,296✔
3757

3758
        replay := fwdPkg.State != channeldb.FwdStateLockedIn
40✔
3759

40✔
3760
        l.log.Debugf("forwarding %d packets to switch: replay=%v",
40✔
3761
                len(switchPackets), replay)
40✔
3762

40✔
3763
        // NOTE: This call is made synchronous so that we ensure all circuits
40✔
3764
        // are committed in the exact order that they are processed in the link.
40✔
3765
        // Failing to do this could cause reorderings/gaps in the range of
40✔
3766
        // opened circuits, which violates assumptions made by the circuit
40✔
3767
        // trimming.
40✔
3768
        l.forwardBatch(replay, switchPackets...)
40✔
3769
}
3770

3771
// processExitHop handles an htlc for which this link is the exit hop. It
3772
// returns a boolean indicating whether the commitment tx needs an update.
3773
func (l *channelLink) processExitHop(pd *lnwallet.PaymentDescriptor,
3774
        obfuscator hop.ErrorEncrypter, fwdInfo hop.ForwardingInfo,
3775
        heightNow uint32, payload invoices.Payload) error {
1,455✔
3776

1,455✔
3777
        // If hodl.ExitSettle is requested, we will not validate the final hop's
1,455✔
3778
        // ADD, nor will we settle the corresponding invoice or respond with the
1,455✔
3779
        // preimage.
1,455✔
3780
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
2,174✔
3781
                l.log.Warnf(hodl.ExitSettle.Warning())
719✔
3782

719✔
3783
                return nil
719✔
3784
        }
719✔
3785

3786
        // As we're the exit hop, we'll double check the hop-payload included in
3787
        // the HTLC to ensure that it was crafted correctly by the sender and
3788
        // is compatible with the HTLC we were extended.
3789
        if pd.Amount < fwdInfo.AmountToForward {
840✔
3790
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
100✔
3791
                        "incompatible value: expected <=%v, got %v", pd.RHash,
100✔
3792
                        pd.Amount, fwdInfo.AmountToForward)
100✔
3793

100✔
3794
                failure := NewLinkError(
100✔
3795
                        lnwire.NewFinalIncorrectHtlcAmount(pd.Amount),
100✔
3796
                )
100✔
3797
                l.sendHTLCError(pd, failure, obfuscator, true)
100✔
3798

100✔
3799
                return nil
100✔
3800
        }
100✔
3801

3802
        // We'll also ensure that our time-lock value has been computed
3803
        // correctly.
3804
        if pd.Timeout < fwdInfo.OutgoingCTLV {
641✔
3805
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
1✔
3806
                        "incompatible time-lock: expected <=%v, got %v",
1✔
3807
                        pd.RHash[:], pd.Timeout, fwdInfo.OutgoingCTLV)
1✔
3808

1✔
3809
                failure := NewLinkError(
1✔
3810
                        lnwire.NewFinalIncorrectCltvExpiry(pd.Timeout),
1✔
3811
                )
1✔
3812
                l.sendHTLCError(pd, failure, obfuscator, true)
1✔
3813

1✔
3814
                return nil
1✔
3815
        }
1✔
3816

3817
        // Notify the invoiceRegistry of the exit hop htlc. If we crash right
3818
        // after this, this code will be re-executed after restart. We will
3819
        // receive back a resolution event.
3820
        invoiceHash := lntypes.Hash(pd.RHash)
639✔
3821

639✔
3822
        circuitKey := models.CircuitKey{
639✔
3823
                ChanID: l.ShortChanID(),
639✔
3824
                HtlcID: pd.HtlcIndex,
639✔
3825
        }
639✔
3826

639✔
3827
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
639✔
3828
                invoiceHash, pd.Amount, pd.Timeout, int32(heightNow),
639✔
3829
                circuitKey, l.hodlQueue.ChanIn(), payload,
639✔
3830
        )
639✔
3831
        if err != nil {
639✔
UNCOV
3832
                return err
×
UNCOV
3833
        }
×
3834

3835
        // Create a hodlHtlc struct and decide either resolved now or later.
3836
        htlc := hodlHtlc{
639✔
3837
                pd:         pd,
639✔
3838
                obfuscator: obfuscator,
639✔
3839
        }
639✔
3840

639✔
3841
        // If the event is nil, the invoice is being held, so we save payment
639✔
3842
        // descriptor for future reference.
639✔
3843
        if event == nil {
1,132✔
3844
                l.hodlMap[circuitKey] = htlc
493✔
3845
                return nil
493✔
3846
        }
493✔
3847

3848
        // Process the received resolution.
3849
        return l.processHtlcResolution(event, htlc)
150✔
3850
}
3851

3852
// settleHTLC settles the HTLC on the channel.
3853
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
3854
        pd *lnwallet.PaymentDescriptor) error {
634✔
3855

634✔
3856
        hash := preimage.Hash()
634✔
3857

634✔
3858
        l.log.Infof("settling htlc %v as exit hop", hash)
634✔
3859

634✔
3860
        err := l.channel.SettleHTLC(
634✔
3861
                preimage, pd.HtlcIndex, pd.SourceRef, nil, nil,
634✔
3862
        )
634✔
3863
        if err != nil {
634✔
UNCOV
3864
                return fmt.Errorf("unable to settle htlc: %w", err)
×
UNCOV
3865
        }
×
3866

3867
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
3868
        // fake one before sending it to the peer.
3869
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
638✔
3870
                l.log.Warnf(hodl.BogusSettle.Warning())
4✔
3871
                preimage = [32]byte{}
4✔
3872
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
4✔
3873
        }
4✔
3874

3875
        // HTLC was successfully settled locally send notification about it
3876
        // remote peer.
3877
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
634✔
3878
                ChanID:          l.ChanID(),
634✔
3879
                ID:              pd.HtlcIndex,
634✔
3880
                PaymentPreimage: preimage,
634✔
3881
        })
634✔
3882

634✔
3883
        // Once we have successfully settled the htlc, notify a settle event.
634✔
3884
        l.cfg.HtlcNotifier.NotifySettleEvent(
634✔
3885
                HtlcKey{
634✔
3886
                        IncomingCircuit: models.CircuitKey{
634✔
3887
                                ChanID: l.ShortChanID(),
634✔
3888
                                HtlcID: pd.HtlcIndex,
634✔
3889
                        },
634✔
3890
                },
634✔
3891
                preimage,
634✔
3892
                HtlcEventTypeReceive,
634✔
3893
        )
634✔
3894

634✔
3895
        return nil
634✔
3896
}
3897

3898
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
3899
// err chan for the individual responses. This method is intended to be spawned
3900
// as a goroutine so the responses can be handled in the background.
3901
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
1,448✔
3902
        // Don't forward packets for which we already have a response in our
1,448✔
3903
        // mailbox. This could happen if a packet fails and is buffered in the
1,448✔
3904
        // mailbox, and the incoming link flaps.
1,448✔
3905
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
1,448✔
3906
        for _, pkt := range packets {
2,896✔
3907
                if l.mailBox.HasPacket(pkt.inKey()) {
1,452✔
3908
                        continue
4✔
3909
                }
3910

3911
                filteredPkts = append(filteredPkts, pkt)
1,448✔
3912
        }
3913

3914
        err := l.cfg.ForwardPackets(l.quit, replay, filteredPkts...)
1,448✔
3915
        if err != nil {
1,459✔
3916
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
3917
                        "settle/fail over htlcswitch: %v", err)
11✔
3918
        }
11✔
3919
}
3920

3921
// sendHTLCError functions cancels HTLC and send cancel message back to the
3922
// peer from which HTLC was received.
3923
func (l *channelLink) sendHTLCError(pd *lnwallet.PaymentDescriptor,
3924
        failure *LinkError, e hop.ErrorEncrypter, isReceive bool) {
109✔
3925

109✔
3926
        reason, err := e.EncryptFirstHop(failure.WireMessage())
109✔
3927
        if err != nil {
109✔
UNCOV
3928
                l.log.Errorf("unable to obfuscate error: %v", err)
×
UNCOV
3929
                return
×
3930
        }
×
3931

3932
        err = l.channel.FailHTLC(pd.HtlcIndex, reason, pd.SourceRef, nil, nil)
109✔
3933
        if err != nil {
109✔
UNCOV
3934
                l.log.Errorf("unable cancel htlc: %v", err)
×
UNCOV
3935
                return
×
UNCOV
3936
        }
×
3937

3938
        // Send the appropriate failure message depending on whether we're
3939
        // in a blinded route or not.
3940
        if err := l.sendIncomingHTLCFailureMsg(
109✔
3941
                pd.HtlcIndex, e, reason,
109✔
3942
        ); err != nil {
109✔
UNCOV
3943
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
UNCOV
3944
                return
×
UNCOV
3945
        }
×
3946

3947
        // Notify a link failure on our incoming link. Outgoing htlc information
3948
        // is not available at this point, because we have not decrypted the
3949
        // onion, so it is excluded.
3950
        var eventType HtlcEventType
109✔
3951
        if isReceive {
218✔
3952
                eventType = HtlcEventTypeReceive
109✔
3953
        } else {
113✔
3954
                eventType = HtlcEventTypeForward
4✔
3955
        }
4✔
3956

3957
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
109✔
3958
                HtlcKey{
109✔
3959
                        IncomingCircuit: models.CircuitKey{
109✔
3960
                                ChanID: l.ShortChanID(),
109✔
3961
                                HtlcID: pd.HtlcIndex,
109✔
3962
                        },
109✔
3963
                },
109✔
3964
                HtlcInfo{
109✔
3965
                        IncomingTimeLock: pd.Timeout,
109✔
3966
                        IncomingAmt:      pd.Amount,
109✔
3967
                },
109✔
3968
                eventType,
109✔
3969
                failure,
109✔
3970
                true,
109✔
3971
        )
109✔
3972
}
3973

3974
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
3975
// peer from which the HTLC was received. This function is primarily used to
3976
// handle the special requirements of route blinding, specifically:
3977
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
3978
// - Introduction nodes should return regular HTLC failure messages.
3979
//
3980
// It accepts the original opaque failure, which will be used in the case
3981
// that we're not part of a blinded route and an error encrypter that'll be
3982
// used if we are the introduction node and need to present an error as if
3983
// we're the failing party.
3984
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
3985
        e hop.ErrorEncrypter,
3986
        originalFailure lnwire.OpaqueReason) error {
125✔
3987

125✔
3988
        var msg lnwire.Message
125✔
3989
        switch {
125✔
3990
        // Our circuit's error encrypter will be nil if this was a locally
3991
        // initiated payment. We can only hit a blinded error for a locally
3992
        // initiated payment if we allow ourselves to be picked as the
3993
        // introduction node for our own payments and in that case we
3994
        // shouldn't reach this code. To prevent the HTLC getting stuck,
3995
        // we fail it back and log an error.
3996
        // code.
3997
        case e == nil:
×
3998
                msg = &lnwire.UpdateFailHTLC{
×
3999
                        ChanID: l.ChanID(),
×
4000
                        ID:     htlcIndex,
×
4001
                        Reason: originalFailure,
×
4002
                }
×
UNCOV
4003

×
UNCOV
4004
                l.log.Errorf("Unexpected blinded failure when "+
×
UNCOV
4005
                        "we are the sending node, incoming htlc: %v(%v)",
×
UNCOV
4006
                        l.ShortChanID(), htlcIndex)
×
4007

4008
        // For cleartext hops (ie, non-blinded/normal) we don't need any
4009
        // transformation on the error message and can just send the original.
4010
        case !e.Type().IsBlinded():
125✔
4011
                msg = &lnwire.UpdateFailHTLC{
125✔
4012
                        ChanID: l.ChanID(),
125✔
4013
                        ID:     htlcIndex,
125✔
4014
                        Reason: originalFailure,
125✔
4015
                }
125✔
4016

4017
        // When we're the introduction node, we need to convert the error to
4018
        // a UpdateFailHTLC.
4019
        case e.Type() == hop.EncrypterTypeIntroduction:
4✔
4020
                l.log.Debugf("Introduction blinded node switching out failure "+
4✔
4021
                        "error: %v", htlcIndex)
4✔
4022

4✔
4023
                // The specification does not require that we set the onion
4✔
4024
                // blob.
4✔
4025
                failureMsg := lnwire.NewInvalidBlinding(nil)
4✔
4026
                reason, err := e.EncryptFirstHop(failureMsg)
4✔
4027
                if err != nil {
4✔
UNCOV
4028
                        return err
×
UNCOV
4029
                }
×
4030

4031
                msg = &lnwire.UpdateFailHTLC{
4✔
4032
                        ChanID: l.ChanID(),
4✔
4033
                        ID:     htlcIndex,
4✔
4034
                        Reason: reason,
4✔
4035
                }
4✔
4036

4037
        // If we are a relaying node, we need to switch out any error that
4038
        // we've received to a malformed HTLC error.
4039
        case e.Type() == hop.EncrypterTypeRelaying:
4✔
4040
                l.log.Debugf("Relaying blinded node switching out malformed "+
4✔
4041
                        "error: %v", htlcIndex)
4✔
4042

4✔
4043
                msg = &lnwire.UpdateFailMalformedHTLC{
4✔
4044
                        ChanID:      l.ChanID(),
4✔
4045
                        ID:          htlcIndex,
4✔
4046
                        FailureCode: lnwire.CodeInvalidBlinding,
4✔
4047
                }
4✔
4048

UNCOV
4049
        default:
×
4050
                return fmt.Errorf("unexpected encrypter: %d", e)
×
4051
        }
4052

4053
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
125✔
UNCOV
4054
                l.log.Warnf("Send update fail failed: %v", err)
×
UNCOV
4055
        }
×
4056

4057
        return nil
125✔
4058
}
4059

4060
// sendMalformedHTLCError helper function which sends the malformed HTLC update
4061
// to the payment sender.
4062
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
4063
        code lnwire.FailCode, onionBlob []byte, sourceRef *channeldb.AddRef) {
7✔
4064

7✔
4065
        shaOnionBlob := sha256.Sum256(onionBlob)
7✔
4066
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
7✔
4067
        if err != nil {
7✔
UNCOV
4068
                l.log.Errorf("unable cancel htlc: %v", err)
×
UNCOV
4069
                return
×
UNCOV
4070
        }
×
4071

4072
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
7✔
4073
                ChanID:       l.ChanID(),
7✔
4074
                ID:           htlcIndex,
7✔
4075
                ShaOnionBlob: shaOnionBlob,
7✔
4076
                FailureCode:  code,
7✔
4077
        })
7✔
4078
}
4079

4080
// fail is a function which is used to encapsulate the action necessary for
4081
// properly failing the link. It takes a LinkFailureError, which will be passed
4082
// to the OnChannelFailure closure, in order for it to determine if we should
4083
// force close the channel, and if we should send an error message to the
4084
// remote peer.
4085
func (l *channelLink) fail(linkErr LinkFailureError,
4086
        format string, a ...interface{}) {
15✔
4087
        reason := fmt.Errorf(format, a...)
15✔
4088

15✔
4089
        // Return if we have already notified about a failure.
15✔
4090
        if l.failed {
15✔
UNCOV
4091
                l.log.Warnf("ignoring link failure (%v), as link already "+
×
UNCOV
4092
                        "failed", reason)
×
UNCOV
4093
                return
×
UNCOV
4094
        }
×
4095

4096
        l.log.Errorf("failing link: %s with error: %v", reason, linkErr)
15✔
4097

15✔
4098
        // Set failed, such that we won't process any more updates, and notify
15✔
4099
        // the peer about the failure.
15✔
4100
        l.failed = true
15✔
4101
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
15✔
4102
}
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