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

lightningnetwork / lnd / 11136034567

02 Oct 2024 01:06AM UTC coverage: 58.817% (+0.003%) from 58.814%
11136034567

push

github

web-flow
Merge pull request #8644 from Roasbeef/remove-sql-mutex-part-deux

kvdb/postgres: remove global application level lock

130416 of 221731 relevant lines covered (58.82%)

28306.61 hits per line

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

80.45
/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
        "github.com/lightningnetwork/lnd/tlv"
35
)
36

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

357
        sync.RWMutex
358

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

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

367
        // log is a link-specific logging instance.
368
        log btclog.Logger
369

370
        // isOutgoingAddBlocked tracks whether the channelLink can send an
371
        // UpdateAddHTLC.
372
        isOutgoingAddBlocked atomic.Bool
373

374
        // isIncomingAddBlocked tracks whether the channelLink can receive an
375
        // UpdateAddHTLC.
376
        isIncomingAddBlocked atomic.Bool
377

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

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

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

390
        wg   sync.WaitGroup
391
        quit chan struct{}
392
}
393

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

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

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

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

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

6✔
431
        return hookID
6✔
432
}
433

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

441
        m.transient = make(map[uint64]func())
4,853✔
442
}
443

444
// hodlHtlc contains htlc data that is required for resolution.
445
type hodlHtlc struct {
446
        add        lnwire.UpdateAddHTLC
447
        sourceRef  channeldb.AddRef
448
        obfuscator hop.ErrorEncrypter
449
}
450

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

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

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

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

476
// A compile time check to ensure channelLink implements the ChannelLink
477
// interface.
478
var _ ChannelLink = (*channelLink)(nil)
479

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

491
        l.log.Info("starting")
215✔
492

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

504
        l.mailBox.ResetMessages()
215✔
505
        l.hodlQueue.Start()
215✔
506

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

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

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

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

549
        l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
215✔
550

215✔
551
        l.wg.Add(1)
215✔
552
        go l.htlcManager()
215✔
553

215✔
554
        return nil
215✔
555
}
556

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

567
        l.log.Info("stopping")
204✔
568

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

204✔
573
        if l.cfg.ChainEvents.Cancel != nil {
208✔
574
                l.cfg.ChainEvents.Cancel()
4✔
575
        }
4✔
576

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

587
        if l.hodlQueue != nil {
408✔
588
                l.hodlQueue.Stop()
204✔
589
        }
204✔
590

591
        close(l.quit)
204✔
592
        l.wg.Wait()
204✔
593

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

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

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

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

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

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

648
        return l.isIncomingAddBlocked.Swap(false)
5✔
649
}
650

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

659
        return !l.isIncomingAddBlocked.Swap(true)
13✔
660
}
661

662
// IsFlushing returns true when UpdateAddHtlc's are disabled in the direction of
663
// the argument.
664
func (l *channelLink) IsFlushing(linkDirection LinkDirection) bool {
4,825✔
665
        if linkDirection == Outgoing {
8,136✔
666
                return l.isOutgoingAddBlocked.Load()
3,311✔
667
        }
3,311✔
668

669
        return l.isIncomingAddBlocked.Load()
1,518✔
670
}
671

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

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

5✔
689
        if direction == Outgoing {
10✔
690
                queue = l.outgoingCommitHooks.newTransients
5✔
691
        } else {
5✔
692
                queue = l.incomingCommitHooks.newTransients
×
693
        }
×
694

695
        select {
5✔
696
        case queue <- hook:
5✔
697
        case <-l.quit:
×
698
        }
699
}
700

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

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

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

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

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

4✔
735
        return feePerKw, nil
4✔
736
}
737

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

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

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

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

762
        // Otherwise, we won't modify our fee.
763
        default:
7✔
764
                return false
7✔
765
        }
766
}
767

768
// failCb is used to cut down on the argument verbosity.
769
type failCb func(update *lnwire.ChannelUpdate1) lnwire.FailureMessage
770

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

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

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

797
        return cb(update)
26✔
798
}
799

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

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

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

822
        var msgsToReSend []lnwire.Message
172✔
823

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

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

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

166✔
847
                        l.log.Infof("resending ChannelReady message to peer")
166✔
848

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

855
                        channelReadyMsg := lnwire.NewChannelReady(
166✔
856
                                l.ChanID(), nextRevocation,
166✔
857
                        )
166✔
858

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

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

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

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

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

172✔
898
                var (
172✔
899
                        openedCircuits []CircuitKey
172✔
900
                        closedCircuits []CircuitKey
172✔
901
                )
172✔
902

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

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

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

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

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

936
        case <-l.quit:
4✔
937
                return ErrLinkShuttingDown
4✔
938
        }
939

940
        return nil
172✔
941
}
942

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

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

215✔
956
        for _, fwdPkg := range fwdPkgs {
225✔
957
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
10✔
958
                        return err
×
959
                }
×
960
        }
961

962
        // If any of our reprocessing steps require an update to the commitment
963
        // txn, we initiate a state transition to capture all relevant changes.
964
        if l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote) > 0 {
219✔
965
                return l.updateCommitTx()
4✔
966
        }
4✔
967

968
        return nil
215✔
969
}
970

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

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

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

994
        // If the package is fully acked but not completed, it must still have
995
        // settles and fails to propagate.
996
        if !fwdPkg.SettleFailFilter.IsFull() {
14✔
997
                l.processRemoteSettleFails(fwdPkg)
4✔
998
        }
4✔
999

1000
        // Finally, replay *ALL ADDS* in this forwarding package. The
1001
        // downstream logic is able to filter out any duplicates, but we must
1002
        // shove the entire, original set of adds down the pipeline so that the
1003
        // batch of adds presented to the sphinx router does not ever change.
1004
        if !fwdPkg.AckFilter.IsFull() {
17✔
1005
                l.processRemoteAdds(fwdPkg)
7✔
1006

7✔
1007
                // If the link failed during processing the adds, we must
7✔
1008
                // return to ensure we won't attempted to update the state
7✔
1009
                // further.
7✔
1010
                if l.failed {
7✔
1011
                        return fmt.Errorf("link failed while " +
×
1012
                                "processing remote adds")
×
1013
                }
×
1014
        }
1015

1016
        return nil
10✔
1017
}
1018

1019
// fwdPkgGarbager periodically reads all forwarding packages from disk and
1020
// removes those that can be discarded. It is safe to do this entirely in the
1021
// background, since all state is coordinated on disk. This also ensures the
1022
// link can continue to process messages and interleave database accesses.
1023
//
1024
// NOTE: This MUST be run as a goroutine.
1025
func (l *channelLink) fwdPkgGarbager() {
215✔
1026
        defer l.wg.Done()
215✔
1027

215✔
1028
        l.cfg.FwdPkgGCTicker.Resume()
215✔
1029
        defer l.cfg.FwdPkgGCTicker.Stop()
215✔
1030

215✔
1031
        if err := l.loadAndRemove(); err != nil {
215✔
1032
                l.log.Warnf("unable to run initial fwd pkgs gc: %v", err)
×
1033
        }
×
1034

1035
        for {
503✔
1036
                select {
288✔
1037
                case <-l.cfg.FwdPkgGCTicker.Ticks():
73✔
1038
                        if err := l.loadAndRemove(); err != nil {
134✔
1039
                                l.log.Warnf("unable to remove fwd pkgs: %v",
61✔
1040
                                        err)
61✔
1041
                                continue
61✔
1042
                        }
1043
                case <-l.quit:
204✔
1044
                        return
204✔
1045
                }
1046
        }
1047
}
1048

1049
// loadAndRemove loads all the channels forwarding packages and determines if
1050
// they can be removed. It is called once before the FwdPkgGCTicker ticks so that
1051
// a longer tick interval can be used.
1052
func (l *channelLink) loadAndRemove() error {
288✔
1053
        fwdPkgs, err := l.channel.LoadFwdPkgs()
288✔
1054
        if err != nil {
349✔
1055
                return err
61✔
1056
        }
61✔
1057

1058
        var removeHeights []uint64
227✔
1059
        for _, fwdPkg := range fwdPkgs {
1,222✔
1060
                if fwdPkg.State != channeldb.FwdStateCompleted {
1,106✔
1061
                        continue
111✔
1062
                }
1063

1064
                removeHeights = append(removeHeights, fwdPkg.Height)
888✔
1065
        }
1066

1067
        // If removeHeights is empty, return early so we don't use a db
1068
        // transaction.
1069
        if len(removeHeights) == 0 {
442✔
1070
                return nil
215✔
1071
        }
215✔
1072

1073
        return l.channel.RemoveFwdPkgs(removeHeights...)
16✔
1074
}
1075

1076
// handleChanSyncErr performs the error handling logic in the case where we
1077
// could not successfully syncChanStates with our channel peer.
1078
func (l *channelLink) handleChanSyncErr(err error) {
4✔
1079
        l.log.Warnf("error when syncing channel states: %v", err)
4✔
1080

4✔
1081
        var errDataLoss *lnwallet.ErrCommitSyncLocalDataLoss
4✔
1082

4✔
1083
        switch {
4✔
1084
        case errors.Is(err, ErrLinkShuttingDown):
4✔
1085
                l.log.Debugf("unable to sync channel states, link is " +
4✔
1086
                        "shutting down")
4✔
1087
                return
4✔
1088

1089
        // We failed syncing the commit chains, probably because the remote has
1090
        // lost state. We should force close the channel.
1091
        case errors.Is(err, lnwallet.ErrCommitSyncRemoteDataLoss):
4✔
1092
                fallthrough
4✔
1093

1094
        // The remote sent us an invalid last commit secret, we should force
1095
        // close the channel.
1096
        // TODO(halseth): and permanently ban the peer?
1097
        case errors.Is(err, lnwallet.ErrInvalidLastCommitSecret):
4✔
1098
                fallthrough
4✔
1099

1100
        // The remote sent us a commit point different from what they sent us
1101
        // before.
1102
        // TODO(halseth): ban peer?
1103
        case errors.Is(err, lnwallet.ErrInvalidLocalUnrevokedCommitPoint):
4✔
1104
                // We'll fail the link and tell the peer to force close the
4✔
1105
                // channel. Note that the database state is not updated here,
4✔
1106
                // but will be updated when the close transaction is ready to
4✔
1107
                // avoid that we go down before storing the transaction in the
4✔
1108
                // db.
4✔
1109
                l.failf(
4✔
1110
                        LinkFailureError{
4✔
1111
                                code:          ErrSyncError,
4✔
1112
                                FailureAction: LinkFailureForceClose,
4✔
1113
                        },
4✔
1114
                        "unable to synchronize channel states: %v", err,
4✔
1115
                )
4✔
1116

1117
        // We have lost state and cannot safely force close the channel. Fail
1118
        // the channel and wait for the remote to hopefully force close it. The
1119
        // remote has sent us its latest unrevoked commitment point, and we'll
1120
        // store it in the database, such that we can attempt to recover the
1121
        // funds if the remote force closes the channel.
1122
        case errors.As(err, &errDataLoss):
4✔
1123
                err := l.channel.MarkDataLoss(
4✔
1124
                        errDataLoss.CommitPoint,
4✔
1125
                )
4✔
1126
                if err != nil {
4✔
1127
                        l.log.Errorf("unable to mark channel data loss: %v",
×
1128
                                err)
×
1129
                }
×
1130

1131
        // We determined the commit chains were not possible to sync. We
1132
        // cautiously fail the channel, but don't force close.
1133
        // TODO(halseth): can we safely force close in any cases where this
1134
        // error is returned?
1135
        case errors.Is(err, lnwallet.ErrCannotSyncCommitChains):
×
1136
                if err := l.channel.MarkBorked(); err != nil {
×
1137
                        l.log.Errorf("unable to mark channel borked: %v", err)
×
1138
                }
×
1139

1140
        // Other, unspecified error.
1141
        default:
×
1142
        }
1143

1144
        l.failf(
4✔
1145
                LinkFailureError{
4✔
1146
                        code:          ErrRecoveryError,
4✔
1147
                        FailureAction: LinkFailureForceNone,
4✔
1148
                },
4✔
1149
                "unable to synchronize channel states: %v", err,
4✔
1150
        )
4✔
1151
}
1152

1153
// htlcManager is the primary goroutine which drives a channel's commitment
1154
// update state-machine in response to messages received via several channels.
1155
// This goroutine reads messages from the upstream (remote) peer, and also from
1156
// downstream channel managed by the channel link. In the event that an htlc
1157
// needs to be forwarded, then send-only forward handler is used which sends
1158
// htlc packets to the switch. Additionally, this goroutine handles acting upon
1159
// all timeouts for any active HTLCs, manages the channel's revocation window,
1160
// and also the htlc trickle queue+timer for this active channels.
1161
//
1162
// NOTE: This MUST be run as a goroutine.
1163
func (l *channelLink) htlcManager() {
215✔
1164
        defer func() {
421✔
1165
                l.cfg.BatchTicker.Stop()
206✔
1166
                l.wg.Done()
206✔
1167
                l.log.Infof("exited")
206✔
1168
        }()
206✔
1169

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

215✔
1172
        // Notify any clients that the link is now in the switch via an
215✔
1173
        // ActiveLinkEvent. We'll also defer an inactive link notification for
215✔
1174
        // when the link exits to ensure that every active notification is
215✔
1175
        // matched by an inactive one.
215✔
1176
        l.cfg.NotifyActiveLink(l.ChannelPoint())
215✔
1177
        defer l.cfg.NotifyInactiveLinkEvent(l.ChannelPoint())
215✔
1178

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

215✔
1181
        // If this isn't the first time that this channel link has been
215✔
1182
        // created, then we'll need to check to see if we need to
215✔
1183
        // re-synchronize state with the remote peer. settledHtlcs is a map of
215✔
1184
        // HTLC's that we re-settled as part of the channel state sync.
215✔
1185
        if l.cfg.SyncStates {
387✔
1186
                err := l.syncChanStates()
172✔
1187
                if err != nil {
176✔
1188
                        l.handleChanSyncErr(err)
4✔
1189
                        return
4✔
1190
                }
4✔
1191
        }
1192

1193
        // If a shutdown message has previously been sent on this link, then we
1194
        // need to make sure that we have disabled any HTLC adds on the outgoing
1195
        // direction of the link and that we re-resend the same shutdown message
1196
        // that we previously sent.
1197
        l.cfg.PreviouslySentShutdown.WhenSome(func(shutdown lnwire.Shutdown) {
219✔
1198
                // Immediately disallow any new outgoing HTLCs.
4✔
1199
                if !l.DisableAdds(Outgoing) {
4✔
1200
                        l.log.Warnf("Outgoing link adds already disabled")
×
1201
                }
×
1202

1203
                // Re-send the shutdown message the peer. Since syncChanStates
1204
                // would have sent any outstanding CommitSig, it is fine for us
1205
                // to immediately queue the shutdown message now.
1206
                err := l.cfg.Peer.SendMessage(false, &shutdown)
4✔
1207
                if err != nil {
4✔
1208
                        l.log.Warnf("Error sending shutdown message: %v", err)
×
1209
                }
×
1210
        })
1211

1212
        // We've successfully reestablished the channel, mark it as such to
1213
        // allow the switch to forward HTLCs in the outbound direction.
1214
        l.markReestablished()
215✔
1215

215✔
1216
        // Now that we've received both channel_ready and channel reestablish,
215✔
1217
        // we can go ahead and send the active channel notification. We'll also
215✔
1218
        // defer the inactive notification for when the link exits to ensure
215✔
1219
        // that every active notification is matched by an inactive one.
215✔
1220
        l.cfg.NotifyActiveChannel(l.ChannelPoint())
215✔
1221
        defer l.cfg.NotifyInactiveChannel(l.ChannelPoint())
215✔
1222

215✔
1223
        // With the channel states synced, we now reset the mailbox to ensure
215✔
1224
        // we start processing all unacked packets in order. This is done here
215✔
1225
        // to ensure that all acknowledgments that occur during channel
215✔
1226
        // resynchronization have taken affect, causing us only to pull unacked
215✔
1227
        // packets after starting to read from the downstream mailbox.
215✔
1228
        l.mailBox.ResetPackets()
215✔
1229

215✔
1230
        // After cleaning up any memory pertaining to incoming packets, we now
215✔
1231
        // replay our forwarding packages to handle any htlcs that can be
215✔
1232
        // processed locally, or need to be forwarded out to the switch. We will
215✔
1233
        // only attempt to resolve packages if our short chan id indicates that
215✔
1234
        // the channel is not pending, otherwise we should have no htlcs to
215✔
1235
        // reforward.
215✔
1236
        if l.ShortChanID() != hop.Source {
430✔
1237
                err := l.resolveFwdPkgs()
215✔
1238
                switch err {
215✔
1239
                // No error was encountered, success.
1240
                case nil:
215✔
1241

1242
                // If the duplicate keystone error was encountered, we'll fail
1243
                // without sending an Error message to the peer.
1244
                case ErrDuplicateKeystone:
×
1245
                        l.failf(LinkFailureError{code: ErrCircuitError},
×
1246
                                "temporary circuit error: %v", err)
×
1247
                        return
×
1248

1249
                // A non-nil error was encountered, send an Error message to
1250
                // the peer.
1251
                default:
×
1252
                        l.failf(LinkFailureError{code: ErrInternalError},
×
1253
                                "unable to resolve fwd pkgs: %v", err)
×
1254
                        return
×
1255
                }
1256

1257
                // With our link's in-memory state fully reconstructed, spawn a
1258
                // goroutine to manage the reclamation of disk space occupied by
1259
                // completed forwarding packages.
1260
                l.wg.Add(1)
215✔
1261
                go l.fwdPkgGarbager()
215✔
1262
        }
1263

1264
        for {
9,491✔
1265
                // We must always check if we failed at some point processing
9,276✔
1266
                // the last update before processing the next.
9,276✔
1267
                if l.failed {
9,285✔
1268
                        l.log.Errorf("link failed, exiting htlcManager")
9✔
1269
                        return
9✔
1270
                }
9✔
1271

1272
                // If the previous event resulted in a non-empty batch, resume
1273
                // the batch ticker so that it can be cleared. Otherwise pause
1274
                // the ticker to prevent waking up the htlcManager while the
1275
                // batch is empty.
1276
                numUpdates := l.channel.NumPendingUpdates(
9,271✔
1277
                        lntypes.Local, lntypes.Remote,
9,271✔
1278
                )
9,271✔
1279
                if numUpdates > 0 {
11,132✔
1280
                        l.cfg.BatchTicker.Resume()
1,861✔
1281
                        l.log.Tracef("BatchTicker resumed, "+
1,861✔
1282
                                "NumPendingUpdates(Local, Remote)=%d",
1,861✔
1283
                                numUpdates,
1,861✔
1284
                        )
1,861✔
1285
                } else {
9,275✔
1286
                        l.cfg.BatchTicker.Pause()
7,414✔
1287
                        l.log.Trace("BatchTicker paused due to zero " +
7,414✔
1288
                                "NumPendingUpdates(Local, Remote)")
7,414✔
1289
                }
7,414✔
1290

1291
                select {
9,271✔
1292
                // We have a new hook that needs to be run when we reach a clean
1293
                // channel state.
1294
                case hook := <-l.flushHooks.newTransients:
5✔
1295
                        if l.channel.IsChannelClean() {
9✔
1296
                                hook()
4✔
1297
                        } else {
9✔
1298
                                l.flushHooks.alloc(hook)
5✔
1299
                        }
5✔
1300

1301
                // We have a new hook that needs to be run when we have
1302
                // committed all of our updates.
1303
                case hook := <-l.outgoingCommitHooks.newTransients:
5✔
1304
                        if !l.channel.OweCommitment() {
9✔
1305
                                hook()
4✔
1306
                        } else {
5✔
1307
                                l.outgoingCommitHooks.alloc(hook)
1✔
1308
                        }
1✔
1309

1310
                // We have a new hook that needs to be run when our peer has
1311
                // committed all of their updates.
1312
                case hook := <-l.incomingCommitHooks.newTransients:
×
1313
                        if !l.channel.NeedCommitment() {
×
1314
                                hook()
×
1315
                        } else {
×
1316
                                l.incomingCommitHooks.alloc(hook)
×
1317
                        }
×
1318

1319
                // Our update fee timer has fired, so we'll check the network
1320
                // fee to see if we should adjust our commitment fee.
1321
                case <-l.updateFeeTimer.C:
4✔
1322
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
4✔
1323

4✔
1324
                        // If we're not the initiator of the channel, don't we
4✔
1325
                        // don't control the fees, so we can ignore this.
4✔
1326
                        if !l.channel.IsInitiator() {
4✔
1327
                                continue
×
1328
                        }
1329

1330
                        // If we are the initiator, then we'll sample the
1331
                        // current fee rate to get into the chain within 3
1332
                        // blocks.
1333
                        netFee, err := l.sampleNetworkFee()
4✔
1334
                        if err != nil {
4✔
1335
                                l.log.Errorf("unable to sample network fee: %v",
×
1336
                                        err)
×
1337
                                continue
×
1338
                        }
1339

1340
                        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
4✔
1341

4✔
1342
                        newCommitFee := l.channel.IdealCommitFeeRate(
4✔
1343
                                netFee, minRelayFee,
4✔
1344
                                l.cfg.MaxAnchorsCommitFeeRate,
4✔
1345
                                l.cfg.MaxFeeAllocation,
4✔
1346
                        )
4✔
1347

4✔
1348
                        // We determine if we should adjust the commitment fee
4✔
1349
                        // based on the current commitment fee, the suggested
4✔
1350
                        // new commitment fee and the current minimum relay fee
4✔
1351
                        // rate.
4✔
1352
                        commitFee := l.channel.CommitFeeRate()
4✔
1353
                        if !shouldAdjustCommitFee(
4✔
1354
                                newCommitFee, commitFee, minRelayFee,
4✔
1355
                        ) {
5✔
1356

1✔
1357
                                continue
1✔
1358
                        }
1359

1360
                        // If we do, then we'll send a new UpdateFee message to
1361
                        // the remote party, to be locked in with a new update.
1362
                        if err := l.updateChannelFee(newCommitFee); err != nil {
3✔
1363
                                l.log.Errorf("unable to update fee rate: %v",
×
1364
                                        err)
×
1365
                                continue
×
1366
                        }
1367

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

4✔
1377
                        // TODO(roasbeef): remove all together
4✔
1378
                        go func() {
8✔
1379
                                chanPoint := l.channel.ChannelPoint()
4✔
1380
                                l.cfg.Peer.WipeChannel(&chanPoint)
4✔
1381
                        }()
4✔
1382

1383
                        return
4✔
1384

1385
                case <-l.cfg.BatchTicker.Ticks():
273✔
1386
                        // Attempt to extend the remote commitment chain
273✔
1387
                        // including all the currently pending entries. If the
273✔
1388
                        // send was unsuccessful, then abandon the update,
273✔
1389
                        // waiting for the revocation window to open up.
273✔
1390
                        if !l.updateCommitTxOrFail() {
273✔
1391
                                return
×
1392
                        }
×
1393

1394
                case <-l.cfg.PendingCommitTicker.Ticks():
2✔
1395
                        l.failf(
2✔
1396
                                LinkFailureError{
2✔
1397
                                        code:          ErrRemoteUnresponsive,
2✔
1398
                                        FailureAction: LinkFailureDisconnect,
2✔
1399
                                },
2✔
1400
                                "unable to complete dance",
2✔
1401
                        )
2✔
1402
                        return
2✔
1403

1404
                // A message from the switch was just received. This indicates
1405
                // that the link is an intermediate hop in a multi-hop HTLC
1406
                // circuit.
1407
                case pkt := <-l.downstream:
1,565✔
1408
                        l.handleDownstreamPkt(pkt)
1,565✔
1409

1410
                // A message from the connected peer was just received. This
1411
                // indicates that we have a new incoming HTLC, either directly
1412
                // for us, or part of a multi-hop HTLC circuit.
1413
                case msg := <-l.upstream:
6,741✔
1414
                        l.handleUpstreamMsg(msg)
6,741✔
1415

1416
                // A htlc resolution is received. This means that we now have a
1417
                // resolution for a previously accepted htlc.
1418
                case hodlItem := <-l.hodlQueue.ChanOut():
492✔
1419
                        htlcResolution := hodlItem.(invoices.HtlcResolution)
492✔
1420
                        err := l.processHodlQueue(htlcResolution)
492✔
1421
                        switch err {
492✔
1422
                        // No error, success.
1423
                        case nil:
491✔
1424

1425
                        // If the duplicate keystone error was encountered,
1426
                        // fail back gracefully.
1427
                        case ErrDuplicateKeystone:
×
1428
                                l.failf(LinkFailureError{
×
1429
                                        code: ErrCircuitError,
×
1430
                                }, "process hodl queue: "+
×
1431
                                        "temporary circuit error: %v",
×
1432
                                        err,
×
1433
                                )
×
1434

1435
                        // Send an Error message to the peer.
1436
                        default:
1✔
1437
                                l.failf(LinkFailureError{
1✔
1438
                                        code: ErrInternalError,
1✔
1439
                                }, "process hodl queue: unable to update "+
1✔
1440
                                        "commitment: %v", err,
1✔
1441
                                )
1✔
1442
                        }
1443

1444
                case <-l.quit:
199✔
1445
                        return
199✔
1446
                }
1447
        }
1448
}
1449

1450
// processHodlQueue processes a received htlc resolution and continues reading
1451
// from the hodl queue until no more resolutions remain. When this function
1452
// returns without an error, the commit tx should be updated.
1453
func (l *channelLink) processHodlQueue(
1454
        firstResolution invoices.HtlcResolution) error {
492✔
1455

492✔
1456
        // Try to read all waiting resolution messages, so that they can all be
492✔
1457
        // processed in a single commitment tx update.
492✔
1458
        htlcResolution := firstResolution
492✔
1459
loop:
492✔
1460
        for {
984✔
1461
                // Lookup all hodl htlcs that can be failed or settled with this event.
492✔
1462
                // The hodl htlc must be present in the map.
492✔
1463
                circuitKey := htlcResolution.CircuitKey()
492✔
1464
                hodlHtlc, ok := l.hodlMap[circuitKey]
492✔
1465
                if !ok {
492✔
1466
                        return fmt.Errorf("hodl htlc not found: %v", circuitKey)
×
1467
                }
×
1468

1469
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
492✔
1470
                        return err
×
1471
                }
×
1472

1473
                // Clean up hodl map.
1474
                delete(l.hodlMap, circuitKey)
492✔
1475

492✔
1476
                select {
492✔
1477
                case item := <-l.hodlQueue.ChanOut():
4✔
1478
                        htlcResolution = item.(invoices.HtlcResolution)
4✔
1479
                default:
492✔
1480
                        break loop
492✔
1481
                }
1482
        }
1483

1484
        // Update the commitment tx.
1485
        if err := l.updateCommitTx(); err != nil {
493✔
1486
                return err
1✔
1487
        }
1✔
1488

1489
        return nil
491✔
1490
}
1491

1492
// processHtlcResolution applies a received htlc resolution to the provided
1493
// htlc. When this function returns without an error, the commit tx should be
1494
// updated.
1495
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1496
        htlc hodlHtlc) error {
638✔
1497

638✔
1498
        circuitKey := resolution.CircuitKey()
638✔
1499

638✔
1500
        // Determine required action for the resolution based on the type of
638✔
1501
        // resolution we have received.
638✔
1502
        switch res := resolution.(type) {
638✔
1503
        // Settle htlcs that returned a settle resolution using the preimage
1504
        // in the resolution.
1505
        case *invoices.HtlcSettleResolution:
634✔
1506
                l.log.Debugf("received settle resolution for %v "+
634✔
1507
                        "with outcome: %v", circuitKey, res.Outcome)
634✔
1508

634✔
1509
                return l.settleHTLC(
634✔
1510
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
634✔
1511
                )
634✔
1512

1513
        // For htlc failures, we get the relevant failure message based
1514
        // on the failure resolution and then fail the htlc.
1515
        case *invoices.HtlcFailResolution:
8✔
1516
                l.log.Debugf("received cancel resolution for "+
8✔
1517
                        "%v with outcome: %v", circuitKey, res.Outcome)
8✔
1518

8✔
1519
                // Get the lnwire failure message based on the resolution
8✔
1520
                // result.
8✔
1521
                failure := getResolutionFailure(res, htlc.add.Amount)
8✔
1522

8✔
1523
                l.sendHTLCError(
8✔
1524
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
8✔
1525
                        true,
8✔
1526
                )
8✔
1527
                return nil
8✔
1528

1529
        // Fail if we do not get a settle of fail resolution, since we
1530
        // are only expecting to handle settles and fails.
1531
        default:
×
1532
                return fmt.Errorf("unknown htlc resolution type: %T",
×
1533
                        resolution)
×
1534
        }
1535
}
1536

1537
// getResolutionFailure returns the wire message that a htlc resolution should
1538
// be failed with.
1539
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1540
        amount lnwire.MilliSatoshi) *LinkError {
8✔
1541

8✔
1542
        // If the resolution has been resolved as part of a MPP timeout,
8✔
1543
        // we need to fail the htlc with lnwire.FailMppTimeout.
8✔
1544
        if resolution.Outcome == invoices.ResultMppTimeout {
8✔
1545
                return NewDetailedLinkError(
×
1546
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
1547
                )
×
1548
        }
×
1549

1550
        // If the htlc is not a MPP timeout, we fail it with
1551
        // FailIncorrectDetails. This error is sent for invoice payment
1552
        // failures such as underpayment/ expiry too soon and hodl invoices
1553
        // (which return FailIncorrectDetails to avoid leaking information).
1554
        incorrectDetails := lnwire.NewFailIncorrectDetails(
8✔
1555
                amount, uint32(resolution.AcceptHeight),
8✔
1556
        )
8✔
1557

8✔
1558
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
8✔
1559
}
1560

1561
// randomFeeUpdateTimeout returns a random timeout between the bounds defined
1562
// within the link's configuration that will be used to determine when the link
1563
// should propose an update to its commitment fee rate.
1564
func (l *channelLink) randomFeeUpdateTimeout() time.Duration {
219✔
1565
        lower := int64(l.cfg.MinUpdateTimeout)
219✔
1566
        upper := int64(l.cfg.MaxUpdateTimeout)
219✔
1567
        return time.Duration(prand.Int63n(upper-lower) + lower)
219✔
1568
}
219✔
1569

1570
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1571
// downstream HTLC Switch.
1572
func (l *channelLink) handleDownstreamUpdateAdd(pkt *htlcPacket) error {
1,524✔
1573
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
1,524✔
1574
        if !ok {
1,524✔
1575
                return errors.New("not an UpdateAddHTLC packet")
×
1576
        }
×
1577

1578
        // If we are flushing the link in the outgoing direction we can't add
1579
        // new htlcs to the link and we need to bounce it
1580
        if l.IsFlushing(Outgoing) {
1,524✔
1581
                l.mailBox.FailAdd(pkt)
×
1582

×
1583
                return NewDetailedLinkError(
×
1584
                        &lnwire.FailPermanentChannelFailure{},
×
1585
                        OutgoingFailureLinkNotEligible,
×
1586
                )
×
1587
        }
×
1588

1589
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1590
        // arbitrary delays between the switch adding an ADD to the
1591
        // mailbox, and the HTLC being added to the commitment state.
1592
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
1,524✔
1593
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
1594
                l.mailBox.AckPacket(pkt.inKey())
×
1595
                return nil
×
1596
        }
×
1597

1598
        // Check if we can add the HTLC here without exceededing the max fee
1599
        // exposure threshold.
1600
        if l.isOverexposedWithHtlc(htlc, false) {
1,528✔
1601
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
4✔
1602
                        "exposure exceeded")
4✔
1603

4✔
1604
                l.mailBox.FailAdd(pkt)
4✔
1605

4✔
1606
                return NewDetailedLinkError(
4✔
1607
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1608
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1609
                )
4✔
1610
        }
4✔
1611

1612
        // A new payment has been initiated via the downstream channel,
1613
        // so we add the new HTLC to our local log, then update the
1614
        // commitment chains.
1615
        htlc.ChanID = l.ChanID()
1,520✔
1616
        openCircuitRef := pkt.inKey()
1,520✔
1617

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

5✔
1630
                // Remove this packet from the link's mailbox, this
5✔
1631
                // prevents it from being reprocessed if the link
5✔
1632
                // restarts and resets it mailbox. If this response
5✔
1633
                // doesn't make it back to the originating link, it will
5✔
1634
                // be rejected upon attempting to reforward the Add to
5✔
1635
                // the switch, since the circuit was never fully opened,
5✔
1636
                // and the forwarding package shows it as
5✔
1637
                // unacknowledged.
5✔
1638
                l.mailBox.FailAdd(pkt)
5✔
1639

5✔
1640
                return NewDetailedLinkError(
5✔
1641
                        lnwire.NewTemporaryChannelFailure(nil),
5✔
1642
                        OutgoingFailureDownstreamHtlcAdd,
5✔
1643
                )
5✔
1644
        }
5✔
1645

1646
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
1,519✔
1647
                "local_log_index=%v, pend_updates=%v",
1,519✔
1648
                htlc.PaymentHash[:], index,
1,519✔
1649
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
1,519✔
1650

1,519✔
1651
        pkt.outgoingChanID = l.ShortChanID()
1,519✔
1652
        pkt.outgoingHTLCID = index
1,519✔
1653
        htlc.ID = index
1,519✔
1654

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

1,519✔
1658
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
1,519✔
1659
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
1,519✔
1660

1,519✔
1661
        _ = l.cfg.Peer.SendMessage(false, htlc)
1,519✔
1662

1,519✔
1663
        // Send a forward event notification to htlcNotifier.
1,519✔
1664
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
1,519✔
1665
                newHtlcKey(pkt),
1,519✔
1666
                HtlcInfo{
1,519✔
1667
                        IncomingTimeLock: pkt.incomingTimeout,
1,519✔
1668
                        IncomingAmt:      pkt.incomingAmount,
1,519✔
1669
                        OutgoingTimeLock: htlc.Expiry,
1,519✔
1670
                        OutgoingAmt:      htlc.Amount,
1,519✔
1671
                },
1,519✔
1672
                getEventType(pkt),
1,519✔
1673
        )
1,519✔
1674

1,519✔
1675
        l.tryBatchUpdateCommitTx()
1,519✔
1676

1,519✔
1677
        return nil
1,519✔
1678
}
1679

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

1693
        case *lnwire.UpdateFulfillHTLC:
27✔
1694
                // If hodl.SettleOutgoing mode is active, we exit early to
27✔
1695
                // simulate arbitrary delays between the switch adding the
27✔
1696
                // SETTLE to the mailbox, and the HTLC being added to the
27✔
1697
                // commitment state.
27✔
1698
                if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
27✔
1699
                        l.log.Warnf(hodl.SettleOutgoing.Warning())
×
1700
                        l.mailBox.AckPacket(pkt.inKey())
×
1701
                        return
×
1702
                }
×
1703

1704
                // An HTLC we forward to the switch has just settled somewhere
1705
                // upstream. Therefore we settle the HTLC within the our local
1706
                // state machine.
1707
                inKey := pkt.inKey()
27✔
1708
                err := l.channel.SettleHTLC(
27✔
1709
                        htlc.PaymentPreimage,
27✔
1710
                        pkt.incomingHTLCID,
27✔
1711
                        pkt.sourceRef,
27✔
1712
                        pkt.destRef,
27✔
1713
                        &inKey,
27✔
1714
                )
27✔
1715
                if err != nil {
27✔
1716
                        l.log.Errorf("unable to settle incoming HTLC for "+
×
1717
                                "circuit-key=%v: %v", inKey, err)
×
1718

×
1719
                        // If the HTLC index for Settle response was not known
×
1720
                        // to our commitment state, it has already been
×
1721
                        // cleaned up by a prior response. We'll thus try to
×
1722
                        // clean up any lingering state to ensure we don't
×
1723
                        // continue reforwarding.
×
1724
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
×
1725
                                l.cleanupSpuriousResponse(pkt)
×
1726
                        }
×
1727

1728
                        // Remove the packet from the link's mailbox to ensure
1729
                        // it doesn't get replayed after a reconnection.
1730
                        l.mailBox.AckPacket(inKey)
×
1731

×
1732
                        return
×
1733
                }
1734

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

27✔
1738
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
27✔
1739

27✔
1740
                // With the HTLC settled, we'll need to populate the wire
27✔
1741
                // message to target the specific channel and HTLC to be
27✔
1742
                // canceled.
27✔
1743
                htlc.ChanID = l.ChanID()
27✔
1744
                htlc.ID = pkt.incomingHTLCID
27✔
1745

27✔
1746
                // Then we send the HTLC settle message to the connected peer
27✔
1747
                // so we can continue the propagation of the settle message.
27✔
1748
                l.cfg.Peer.SendMessage(false, htlc)
27✔
1749

27✔
1750
                // Send a settle event notification to htlcNotifier.
27✔
1751
                l.cfg.HtlcNotifier.NotifySettleEvent(
27✔
1752
                        newHtlcKey(pkt),
27✔
1753
                        htlc.PaymentPreimage,
27✔
1754
                        getEventType(pkt),
27✔
1755
                )
27✔
1756

27✔
1757
                // Immediately update the commitment tx to minimize latency.
27✔
1758
                l.updateCommitTxOrFail()
27✔
1759

1760
        case *lnwire.UpdateFailHTLC:
22✔
1761
                // If hodl.FailOutgoing mode is active, we exit early to
22✔
1762
                // simulate arbitrary delays between the switch adding a FAIL to
22✔
1763
                // the mailbox, and the HTLC being added to the commitment
22✔
1764
                // state.
22✔
1765
                if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
22✔
1766
                        l.log.Warnf(hodl.FailOutgoing.Warning())
×
1767
                        l.mailBox.AckPacket(pkt.inKey())
×
1768
                        return
×
1769
                }
×
1770

1771
                // An HTLC cancellation has been triggered somewhere upstream,
1772
                // we'll remove then HTLC from our local state machine.
1773
                inKey := pkt.inKey()
22✔
1774
                err := l.channel.FailHTLC(
22✔
1775
                        pkt.incomingHTLCID,
22✔
1776
                        htlc.Reason,
22✔
1777
                        pkt.sourceRef,
22✔
1778
                        pkt.destRef,
22✔
1779
                        &inKey,
22✔
1780
                )
22✔
1781
                if err != nil {
28✔
1782
                        l.log.Errorf("unable to cancel incoming HTLC for "+
6✔
1783
                                "circuit-key=%v: %v", inKey, err)
6✔
1784

6✔
1785
                        // If the HTLC index for Fail response was not known to
6✔
1786
                        // our commitment state, it has already been cleaned up
6✔
1787
                        // by a prior response. We'll thus try to clean up any
6✔
1788
                        // lingering state to ensure we don't continue
6✔
1789
                        // reforwarding.
6✔
1790
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
8✔
1791
                                l.cleanupSpuriousResponse(pkt)
2✔
1792
                        }
2✔
1793

1794
                        // Remove the packet from the link's mailbox to ensure
1795
                        // it doesn't get replayed after a reconnection.
1796
                        l.mailBox.AckPacket(inKey)
6✔
1797

6✔
1798
                        return
6✔
1799
                }
1800

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

20✔
1804
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
20✔
1805

20✔
1806
                // With the HTLC removed, we'll need to populate the wire
20✔
1807
                // message to target the specific channel and HTLC to be
20✔
1808
                // canceled. The "Reason" field will have already been set
20✔
1809
                // within the switch.
20✔
1810
                htlc.ChanID = l.ChanID()
20✔
1811
                htlc.ID = pkt.incomingHTLCID
20✔
1812

20✔
1813
                // We send the HTLC message to the peer which initially created
20✔
1814
                // the HTLC. If the incoming blinding point is non-nil, we
20✔
1815
                // know that we are a relaying node in a blinded path.
20✔
1816
                // Otherwise, we're either an introduction node or not part of
20✔
1817
                // a blinded path at all.
20✔
1818
                if err := l.sendIncomingHTLCFailureMsg(
20✔
1819
                        htlc.ID,
20✔
1820
                        pkt.obfuscator,
20✔
1821
                        htlc.Reason,
20✔
1822
                ); err != nil {
20✔
1823
                        l.log.Errorf("unable to send HTLC failure: %v",
×
1824
                                err)
×
1825

×
1826
                        return
×
1827
                }
×
1828

1829
                // If the packet does not have a link failure set, it failed
1830
                // further down the route so we notify a forwarding failure.
1831
                // Otherwise, we notify a link failure because it failed at our
1832
                // node.
1833
                if pkt.linkFailure != nil {
34✔
1834
                        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
14✔
1835
                                newHtlcKey(pkt),
14✔
1836
                                newHtlcInfo(pkt),
14✔
1837
                                getEventType(pkt),
14✔
1838
                                pkt.linkFailure,
14✔
1839
                                false,
14✔
1840
                        )
14✔
1841
                } else {
24✔
1842
                        l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
10✔
1843
                                newHtlcKey(pkt), getEventType(pkt),
10✔
1844
                        )
10✔
1845
                }
10✔
1846

1847
                // Immediately update the commitment tx to minimize latency.
1848
                l.updateCommitTxOrFail()
20✔
1849
        }
1850
}
1851

1852
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1853
// full.
1854
func (l *channelLink) tryBatchUpdateCommitTx() {
1,519✔
1855
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
1,519✔
1856
        if pending < uint64(l.cfg.BatchSize) {
2,400✔
1857
                return
881✔
1858
        }
881✔
1859

1860
        l.updateCommitTxOrFail()
642✔
1861
}
1862

1863
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1864
// associated with this packet. If successful in doing so, it will also purge
1865
// the open circuit from the circuit map and remove the packet from the link's
1866
// mailbox.
1867
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
2✔
1868
        inKey := pkt.inKey()
2✔
1869

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

2✔
1873
        // If the htlc packet doesn't have a source reference, it is unsafe to
2✔
1874
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
2✔
1875
        if pkt.sourceRef == nil {
3✔
1876
                l.log.Errorf("unable to cleanup response for incoming "+
1✔
1877
                        "circuit-key=%v, does not contain source reference",
1✔
1878
                        inKey)
1✔
1879
                return
1✔
1880
        }
1✔
1881

1882
        // If the source reference is present,  we will try to prevent this link
1883
        // from resending the packet to the switch. To do so, we ack the AddRef
1884
        // of the incoming HTLC belonging to this link.
1885
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
1✔
1886
        if err != nil {
1✔
1887
                l.log.Errorf("unable to ack AddRef for incoming "+
×
1888
                        "circuit-key=%v: %v", inKey, err)
×
1889

×
1890
                // If this operation failed, it is unsafe to attempt removal of
×
1891
                // the destination reference or circuit, so we exit early. The
×
1892
                // cleanup may proceed with a different packet in the future
×
1893
                // that succeeds on this step.
×
1894
                return
×
1895
        }
×
1896

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

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

1✔
1918
        // With all known references acked, we can now safely delete the circuit
1✔
1919
        // from the switch's circuit map, as the state is no longer needed.
1✔
1920
        err = l.cfg.Circuits.DeleteCircuits(inKey)
1✔
1921
        if err != nil {
1✔
1922
                l.log.Errorf("unable to delete circuit for "+
×
1923
                        "circuit-key=%v: %v", inKey, err)
×
1924
        }
×
1925
}
1926

1927
// handleUpstreamMsg processes wire messages related to commitment state
1928
// updates from the upstream peer. The upstream peer is the peer whom we have a
1929
// direct channel with, updating our respective commitment chains.
1930
func (l *channelLink) handleUpstreamMsg(msg lnwire.Message) {
6,741✔
1931
        switch msg := msg.(type) {
6,741✔
1932
        case *lnwire.UpdateAddHTLC:
1,494✔
1933
                if l.IsFlushing(Incoming) {
1,494✔
1934
                        // This is forbidden by the protocol specification.
×
1935
                        // The best chance we have to deal with this is to drop
×
1936
                        // the connection. This should roll back the channel
×
1937
                        // state to the last CommitSig. If the remote has
×
1938
                        // already sent a CommitSig we haven't received yet,
×
1939
                        // channel state will be re-synchronized with a
×
1940
                        // ChannelReestablish message upon reconnection and the
×
1941
                        // protocol state that caused us to flush the link will
×
1942
                        // be rolled back. In the event that there was some
×
1943
                        // non-deterministic behavior in the remote that caused
×
1944
                        // them to violate the protocol, we have a decent shot
×
1945
                        // at correcting it this way, since reconnecting will
×
1946
                        // put us in the cleanest possible state to try again.
×
1947
                        //
×
1948
                        // In addition to the above, it is possible for us to
×
1949
                        // hit this case in situations where we improperly
×
1950
                        // handle message ordering due to concurrency choices.
×
1951
                        // An issue has been filed to address this here:
×
1952
                        // https://github.com/lightningnetwork/lnd/issues/8393
×
1953
                        l.failf(
×
1954
                                LinkFailureError{
×
1955
                                        code:             ErrInvalidUpdate,
×
1956
                                        FailureAction:    LinkFailureDisconnect,
×
1957
                                        PermanentFailure: false,
×
1958
                                        Warning:          true,
×
1959
                                },
×
1960
                                "received add while link is flushing",
×
1961
                        )
×
1962

×
1963
                        return
×
1964
                }
×
1965

1966
                // Disallow htlcs with blinding points set if we haven't
1967
                // enabled the feature. This saves us from having to process
1968
                // the onion at all, but will only catch blinded payments
1969
                // where we are a relaying node (as the blinding point will
1970
                // be in the payload when we're the introduction node).
1971
                if msg.BlindingPoint.IsSome() && l.cfg.DisallowRouteBlinding {
1,494✔
1972
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
1973
                                "blinding point included when route blinding "+
×
1974
                                        "is disabled")
×
1975

×
1976
                        return
×
1977
                }
×
1978

1979
                // We have to check the limit here rather than later in the
1980
                // switch because the counterparty can keep sending HTLC's
1981
                // without sending a revoke. This would mean that the switch
1982
                // check would only occur later.
1983
                if l.isOverexposedWithHtlc(msg, true) {
1,494✔
1984
                        l.failf(LinkFailureError{code: ErrInternalError},
×
1985
                                "peer sent us an HTLC that exceeded our max "+
×
1986
                                        "fee exposure")
×
1987

×
1988
                        return
×
1989
                }
×
1990

1991
                // We just received an add request from an upstream peer, so we
1992
                // add it to our state machine, then add the HTLC to our
1993
                // "settle" list in the event that we know the preimage.
1994
                index, err := l.channel.ReceiveHTLC(msg)
1,494✔
1995
                if err != nil {
1,494✔
1996
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
1997
                                "unable to handle upstream add HTLC: %v", err)
×
1998
                        return
×
1999
                }
×
2000

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

2004
        case *lnwire.UpdateFulfillHTLC:
664✔
2005
                pre := msg.PaymentPreimage
664✔
2006
                idx := msg.ID
664✔
2007

664✔
2008
                // Before we pipeline the settle, we'll check the set of active
664✔
2009
                // htlc's to see if the related UpdateAddHTLC has been fully
664✔
2010
                // locked-in.
664✔
2011
                var lockedin bool
664✔
2012
                htlcs := l.channel.ActiveHtlcs()
664✔
2013
                for _, add := range htlcs {
43,242✔
2014
                        // The HTLC will be outgoing and match idx.
42,578✔
2015
                        if !add.Incoming && add.HtlcIndex == idx {
43,240✔
2016
                                lockedin = true
662✔
2017
                                break
662✔
2018
                        }
2019
                }
2020

2021
                if !lockedin {
666✔
2022
                        l.failf(
2✔
2023
                                LinkFailureError{code: ErrInvalidUpdate},
2✔
2024
                                "unable to handle upstream settle",
2✔
2025
                        )
2✔
2026
                        return
2✔
2027
                }
2✔
2028

2029
                if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
666✔
2030
                        l.failf(
4✔
2031
                                LinkFailureError{
4✔
2032
                                        code:          ErrInvalidUpdate,
4✔
2033
                                        FailureAction: LinkFailureForceClose,
4✔
2034
                                },
4✔
2035
                                "unable to handle upstream settle HTLC: %v", err,
4✔
2036
                        )
4✔
2037
                        return
4✔
2038
                }
4✔
2039

2040
                settlePacket := &htlcPacket{
662✔
2041
                        outgoingChanID: l.ShortChanID(),
662✔
2042
                        outgoingHTLCID: idx,
662✔
2043
                        htlc: &lnwire.UpdateFulfillHTLC{
662✔
2044
                                PaymentPreimage: pre,
662✔
2045
                        },
662✔
2046
                }
662✔
2047

662✔
2048
                // Add the newly discovered preimage to our growing list of
662✔
2049
                // uncommitted preimage. These will be written to the witness
662✔
2050
                // cache just before accepting the next commitment signature
662✔
2051
                // from the remote peer.
662✔
2052
                l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
662✔
2053

662✔
2054
                // Pipeline this settle, send it to the switch.
662✔
2055
                go l.forwardBatch(false, settlePacket)
662✔
2056

2057
        case *lnwire.UpdateFailMalformedHTLC:
7✔
2058
                // Convert the failure type encoded within the HTLC fail
7✔
2059
                // message to the proper generic lnwire error code.
7✔
2060
                var failure lnwire.FailureMessage
7✔
2061
                switch msg.FailureCode {
7✔
2062
                case lnwire.CodeInvalidOnionVersion:
5✔
2063
                        failure = &lnwire.FailInvalidOnionVersion{
5✔
2064
                                OnionSHA256: msg.ShaOnionBlob,
5✔
2065
                        }
5✔
2066
                case lnwire.CodeInvalidOnionHmac:
×
2067
                        failure = &lnwire.FailInvalidOnionHmac{
×
2068
                                OnionSHA256: msg.ShaOnionBlob,
×
2069
                        }
×
2070

2071
                case lnwire.CodeInvalidOnionKey:
×
2072
                        failure = &lnwire.FailInvalidOnionKey{
×
2073
                                OnionSHA256: msg.ShaOnionBlob,
×
2074
                        }
×
2075

2076
                // Handle malformed errors that are part of a blinded route.
2077
                // This case is slightly different, because we expect every
2078
                // relaying node in the blinded portion of the route to send
2079
                // malformed errors. If we're also a relaying node, we're
2080
                // likely going to switch this error out anyway for our own
2081
                // malformed error, but we handle the case here for
2082
                // completeness.
2083
                case lnwire.CodeInvalidBlinding:
4✔
2084
                        failure = &lnwire.FailInvalidBlinding{
4✔
2085
                                OnionSHA256: msg.ShaOnionBlob,
4✔
2086
                        }
4✔
2087

2088
                default:
2✔
2089
                        l.log.Warnf("unexpected failure code received in "+
2✔
2090
                                "UpdateFailMailformedHTLC: %v", msg.FailureCode)
2✔
2091

2✔
2092
                        // We don't just pass back the error we received from
2✔
2093
                        // our successor. Otherwise we might report a failure
2✔
2094
                        // that penalizes us more than needed. If the onion that
2✔
2095
                        // we forwarded was correct, the node should have been
2✔
2096
                        // able to send back its own failure. The node did not
2✔
2097
                        // send back its own failure, so we assume there was a
2✔
2098
                        // problem with the onion and report that back. We reuse
2✔
2099
                        // the invalid onion key failure because there is no
2✔
2100
                        // specific error for this case.
2✔
2101
                        failure = &lnwire.FailInvalidOnionKey{
2✔
2102
                                OnionSHA256: msg.ShaOnionBlob,
2✔
2103
                        }
2✔
2104
                }
2105

2106
                // With the error parsed, we'll convert the into it's opaque
2107
                // form.
2108
                var b bytes.Buffer
7✔
2109
                if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
7✔
2110
                        l.log.Errorf("unable to encode malformed error: %v", err)
×
2111
                        return
×
2112
                }
×
2113

2114
                // If remote side have been unable to parse the onion blob we
2115
                // have sent to it, than we should transform the malformed HTLC
2116
                // message to the usual HTLC fail message.
2117
                err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
7✔
2118
                if err != nil {
7✔
2119
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2120
                                "unable to handle upstream fail HTLC: %v", err)
×
2121
                        return
×
2122
                }
×
2123

2124
        case *lnwire.UpdateFailHTLC:
124✔
2125
                // Verify that the failure reason is at least 256 bytes plus
124✔
2126
                // overhead.
124✔
2127
                const minimumFailReasonLength = lnwire.FailureMessageLength +
124✔
2128
                        2 + 2 + 32
124✔
2129

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

×
2149
                                return
×
2150
                        }
×
2151
                }
2152

2153
                // Add fail to the update log.
2154
                idx := msg.ID
124✔
2155
                err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
124✔
2156
                if err != nil {
124✔
2157
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2158
                                "unable to handle upstream fail HTLC: %v", err)
×
2159
                        return
×
2160
                }
×
2161

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

2184
                // Instead of truncating the slice to conserve memory
2185
                // allocations, we simply set the uncommitted preimage slice to
2186
                // nil so that a new one will be initialized if any more
2187
                // witnesses are discovered. We do this because the maximum size
2188
                // that the slice can occupy is 15KB, and we want to ensure we
2189
                // release that memory back to the runtime.
2190
                l.uncommittedPreimages = nil
2,241✔
2191

2,241✔
2192
                // We just received a new updates to our local commitment
2,241✔
2193
                // chain, validate this new commitment, closing the link if
2,241✔
2194
                // invalid.
2,241✔
2195
                auxSigBlob, err := msg.CustomRecords.Serialize()
2,241✔
2196
                if err != nil {
2,241✔
2197
                        l.failf(
×
2198
                                LinkFailureError{code: ErrInvalidCommitment},
×
2199
                                "unable to serialize custom records: %v", err,
×
2200
                        )
×
2201

×
2202
                        return
×
2203
                }
×
2204
                err = l.channel.ReceiveNewCommitment(&lnwallet.CommitSigs{
2,241✔
2205
                        CommitSig:  msg.CommitSig,
2,241✔
2206
                        HtlcSigs:   msg.HtlcSigs,
2,241✔
2207
                        PartialSig: msg.PartialSig,
2,241✔
2208
                        AuxSigBlob: auxSigBlob,
2,241✔
2209
                })
2,241✔
2210
                if err != nil {
2,241✔
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) {
×
2217
                        case *lnwallet.InvalidCommitSigError:
×
2218
                                sendData = []byte(err.Error())
×
2219
                        case *lnwallet.InvalidHtlcSigError:
×
2220
                                sendData = []byte(err.Error())
×
2221
                        }
2222
                        l.failf(
×
2223
                                LinkFailureError{
×
2224
                                        code:          ErrInvalidCommitment,
×
2225
                                        FailureAction: LinkFailureForceClose,
×
2226
                                        SendData:      sendData,
×
2227
                                },
×
2228
                                "ChannelPoint(%v): unable to accept new "+
×
2229
                                        "commitment: %v",
×
2230
                                l.channel.ChannelPoint(), err,
×
2231
                        )
×
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,241✔
2239
                        l.channel.RevokeCurrentCommitment()
2,241✔
2240
                if err != nil {
2,241✔
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.failf(
×
2252
                                LinkFailureError{
×
2253
                                        code:          ErrInternalError,
×
2254
                                        Warning:       true,
×
2255
                                        FailureAction: LinkFailureDisconnect,
×
2256
                                },
×
2257
                                "ChannelPoint(%v): unable to accept new "+
×
2258
                                        "commitment: %v",
×
2259
                                l.channel.ChannelPoint(), err,
×
2260
                        )
×
2261
                        return
×
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,241✔
2267
                l.incomingCommitHooks.invoke()
2,241✔
2268
                l.RWMutex.Unlock()
2,241✔
2269

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

2,241✔
2272
                // Notify the incoming htlcs of which the resolutions were
2,241✔
2273
                // locked in.
2,241✔
2274
                for id, settled := range finalHTLCs {
3,013✔
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,241✔
2291
                        HtlcKey: contractcourt.LocalHtlcSet,
2,241✔
2292
                        Htlcs:   currentHtlcs,
2,241✔
2293
                }
2,241✔
2294
                err = l.cfg.NotifyContractUpdate(newUpdate)
2,241✔
2295
                if err != nil {
2,241✔
2296
                        l.log.Errorf("unable to notify contract update: %v",
×
2297
                                err)
×
2298
                        return
×
2299
                }
×
2300

2301
                select {
2,241✔
2302
                case <-l.quit:
4✔
2303
                        return
4✔
2304
                default:
2,237✔
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,479✔
2314
                        if !l.updateCommitTxOrFail() {
1,242✔
2315
                                return
×
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,237✔
2323
                if l.channel.IsChannelClean() {
2,448✔
2324
                        l.flushHooks.invoke()
211✔
2325
                }
211✔
2326
                l.RWMutex.Unlock()
2,237✔
2327

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

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

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

2362
                select {
2,227✔
2363
                case <-l.quit:
2✔
2364
                        return
2✔
2365
                default:
2,225✔
2366
                }
2367

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

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

2385
                l.processRemoteSettleFails(fwdPkg)
2,225✔
2386
                l.processRemoteAdds(fwdPkg)
2,225✔
2387

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

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

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

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

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

×
2430
                        return
×
2431
                }
×
2432

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

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

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

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

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

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

2482
}
2483

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

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

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

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

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

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

2,412✔
2538
        return nil
2,412✔
2539
}
2540

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

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

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

2564
        return true
2,735✔
2565
}
2566

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

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

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

2593
        newCommit, err := l.channel.SignNextCommitment()
3,224✔
2594
        if err == lnwallet.ErrNoWindow {
4,208✔
2595
                l.cfg.PendingCommitTicker.Resume()
984✔
2596
                l.log.Trace("PendingCommitTicker resumed")
984✔
2597

984✔
2598
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
984✔
2599
                l.log.Tracef("revocation window exhausted, unable to send: "+
984✔
2600
                        "%v, pend_updates=%v, dangling_closes%v", n,
984✔
2601
                        lnutils.SpewLogClosure(l.openedCircuits),
984✔
2602
                        lnutils.SpewLogClosure(l.closedCircuits))
984✔
2603

984✔
2604
                return nil
984✔
2605
        } else if err != nil {
3,228✔
2606
                return err
×
2607
        }
×
2608

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

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

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

2629
        select {
2,244✔
2630
        case <-l.quit:
3✔
2631
                return ErrLinkShuttingDown
3✔
2632
        default:
2,241✔
2633
        }
2634

2635
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
2,241✔
2636
        if err != nil {
2,241✔
2637
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
2638
        }
×
2639

2640
        commitSig := &lnwire.CommitSig{
2,241✔
2641
                ChanID:        l.ChanID(),
2,241✔
2642
                CommitSig:     newCommit.CommitSig,
2,241✔
2643
                HtlcSigs:      newCommit.HtlcSigs,
2,241✔
2644
                PartialSig:    newCommit.PartialSig,
2,241✔
2645
                CustomRecords: auxBlobRecords,
2,241✔
2646
        }
2,241✔
2647
        l.cfg.Peer.SendMessage(false, commitSig)
2,241✔
2648

2,241✔
2649
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
2,241✔
2650
        // of commit hooks.
2,241✔
2651
        l.RWMutex.Lock()
2,241✔
2652
        l.outgoingCommitHooks.invoke()
2,241✔
2653
        l.RWMutex.Unlock()
2,241✔
2654

2,241✔
2655
        return nil
2,241✔
2656
}
2657

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

2666
// ChannelPoint returns the channel outpoint for the channel link.
2667
// NOTE: Part of the ChannelLink interface.
2668
func (l *channelLink) ChannelPoint() wire.OutPoint {
848✔
2669
        return l.channel.ChannelPoint()
848✔
2670
}
848✔
2671

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

9,921✔
2681
        return l.channel.ShortChanID()
9,921✔
2682
}
9,921✔
2683

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

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

2703
        return hop.Source, nil
4✔
2704
}
2705

2706
// ChanID returns the channel ID for the channel link. The channel ID is a more
2707
// compact representation of a channel's full outpoint.
2708
//
2709
// NOTE: Part of the ChannelLink interface.
2710
func (l *channelLink) ChanID() lnwire.ChannelID {
7,149✔
2711
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
7,149✔
2712
}
7,149✔
2713

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

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

2735
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2736
// method.
2737
//
2738
// NOTE: Part of the dustHandler interface.
2739
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2740
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
8,014✔
2741

8,014✔
2742
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
8,014✔
2743
}
8,014✔
2744

2745
// getFeeRate is a wrapper method that retrieves the underlying channel's
2746
// feerate.
2747
//
2748
// NOTE: Part of the dustHandler interface.
2749
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
1,823✔
2750
        return l.channel.CommitFeeRate()
1,823✔
2751
}
1,823✔
2752

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

4,833✔
2762
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
4,833✔
2763
}
4,833✔
2764

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

2775
        return l.channel.State().LocalCommitment.CommitFee
3,014✔
2776
}
2777

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

6✔
2792
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
6✔
2793

6✔
2794
        // Get the sum of dust for both the local and remote commitments using
6✔
2795
        // this "dry-run" fee.
6✔
2796
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
6✔
2797
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
6✔
2798

6✔
2799
        // Calculate the local and remote commitment fees using this dry-run
6✔
2800
        // fee.
6✔
2801
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
6✔
2802
        if err != nil {
6✔
2803
                return false, err
×
2804
        }
×
2805

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

2813
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
6✔
2814
                remoteFee,
6✔
2815
        )
6✔
2816

6✔
2817
        return totalRemoteDust > l.cfg.MaxFeeExposure, nil
6✔
2818
}
2819

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

3,014✔
2831
        dustClosure := l.getDustClosure()
3,014✔
2832

3,014✔
2833
        feeRate := l.channel.WorstCaseFeeRate()
3,014✔
2834

3,014✔
2835
        amount := htlc.Amount.ToSatoshis()
3,014✔
2836

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

3,014✔
2841
        // Calculate the dust sum for the local and remote commitments.
3,014✔
2842
        localDustSum := l.getDustSum(
3,014✔
2843
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
3,014✔
2844
        )
3,014✔
2845
        remoteDustSum := l.getDustSum(
3,014✔
2846
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
3,014✔
2847
        )
3,014✔
2848

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

3,014✔
2852
        if l.getCommitFee(true) > commitFee {
3,464✔
2853
                commitFee = l.getCommitFee(true)
450✔
2854
        }
450✔
2855

2856
        localDustSum += lnwire.NewMSatFromSatoshis(commitFee)
3,014✔
2857
        remoteDustSum += lnwire.NewMSatFromSatoshis(commitFee)
3,014✔
2858

3,014✔
2859
        // Calculate the additional fee increase if this is a non-dust HTLC.
3,014✔
2860
        weight := lntypes.WeightUnit(input.HTLCWeight)
3,014✔
2861
        additional := lnwire.NewMSatFromSatoshis(
3,014✔
2862
                feeRate.FeeForWeight(weight),
3,014✔
2863
        )
3,014✔
2864

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

2875
        if localDustSum > l.cfg.MaxFeeExposure {
3,018✔
2876
                // The max fee exposure was exceeded.
4✔
2877
                return true
4✔
2878
        }
4✔
2879

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

2890
        return remoteDustSum > l.cfg.MaxFeeExposure
3,010✔
2891
}
2892

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

2901
// dustHelper is used to construct the dustClosure.
2902
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
2903
        remoteDustLimit btcutil.Amount) dustClosure {
5,033✔
2904

5,033✔
2905
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
5,033✔
2906
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
73,939✔
2907

68,906✔
2908
                var dustLimit btcutil.Amount
68,906✔
2909
                if whoseCommit.IsLocal() {
103,361✔
2910
                        dustLimit = localDustLimit
34,455✔
2911
                } else {
68,910✔
2912
                        dustLimit = remoteDustLimit
34,455✔
2913
                }
34,455✔
2914

2915
                return lnwallet.HtlcIsDust(
68,906✔
2916
                        chantype, incoming, whoseCommit, feerate, amt,
68,906✔
2917
                        dustLimit,
68,906✔
2918
                )
68,906✔
2919
        }
2920

2921
        return isDust
5,033✔
2922
}
2923

2924
// zeroConfConfirmed returns whether or not the zero-conf channel has
2925
// confirmed on-chain.
2926
//
2927
// Part of the scidAliasHandler interface.
2928
func (l *channelLink) zeroConfConfirmed() bool {
7✔
2929
        return l.channel.State().ZeroConfConfirmed()
7✔
2930
}
7✔
2931

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

2940
// isZeroConf returns whether or not the underlying channel is a zero-conf
2941
// channel.
2942
//
2943
// Part of the scidAliasHandler interface.
2944
func (l *channelLink) isZeroConf() bool {
215✔
2945
        return l.channel.State().IsZeroConf()
215✔
2946
}
215✔
2947

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

2958
// getAliases returns the set of aliases for the underlying channel.
2959
//
2960
// Part of the scidAliasHandler interface.
2961
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
221✔
2962
        return l.cfg.GetAliases(l.ShortChanID())
221✔
2963
}
221✔
2964

2965
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
2966
//
2967
// Part of the scidAliasHandler interface.
2968
func (l *channelLink) attachFailAliasUpdate(closure func(
2969
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
216✔
2970

216✔
2971
        l.Lock()
216✔
2972
        l.cfg.FailAliasUpdate = closure
216✔
2973
        l.Unlock()
216✔
2974
}
216✔
2975

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

215✔
2986
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
215✔
2987
        // never committed.
215✔
2988
        l.mailBox.SetFeeRate(l.getFeeRate())
215✔
2989

215✔
2990
        // Also set the mailbox's dust closure so that it can query whether HTLC's
215✔
2991
        // are dust given the current feerate.
215✔
2992
        l.mailBox.SetDustClosure(l.getDustClosure())
215✔
2993
}
215✔
2994

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

16✔
3005
        l.Lock()
16✔
3006
        defer l.Unlock()
16✔
3007

16✔
3008
        l.cfg.FwrdingPolicy = newPolicy
16✔
3009
}
16✔
3010

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

53✔
3024
        l.RLock()
53✔
3025
        policy := l.cfg.FwrdingPolicy
53✔
3026
        l.RUnlock()
53✔
3027

53✔
3028
        // Using the outgoing HTLC amount, we'll calculate the outgoing
53✔
3029
        // fee this incoming HTLC must carry in order to satisfy the constraints
53✔
3030
        // of the outgoing link.
53✔
3031
        outFee := ExpectedFee(policy, amtToForward)
53✔
3032

53✔
3033
        // Then calculate the inbound fee that we charge based on the sum of
53✔
3034
        // outgoing HTLC amount and outgoing fee.
53✔
3035
        inFee := inboundFee.CalcFee(amtToForward + outFee)
53✔
3036

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

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

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

3068
        // Check whether the outgoing htlc satisfies the channel policy.
3069
        err := l.canSendHtlc(
47✔
3070
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
47✔
3071
                originalScid,
47✔
3072
        )
47✔
3073
        if err != nil {
64✔
3074
                return err
17✔
3075
        }
17✔
3076

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

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

3098
        return nil
32✔
3099
}
3100

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

1,562✔
3110
        l.RLock()
1,562✔
3111
        policy := l.cfg.FwrdingPolicy
1,562✔
3112
        l.RUnlock()
1,562✔
3113

1,562✔
3114
        // We pass in hop.Source here as this is only used in the Switch when
1,562✔
3115
        // trying to send over a local link. This causes the fallback mechanism
1,562✔
3116
        // to occur.
1,562✔
3117
        return l.canSendHtlc(
1,562✔
3118
                policy, payHash, amt, timeout, heightNow, hop.Source,
1,562✔
3119
        )
1,562✔
3120
}
1,562✔
3121

3122
// canSendHtlc checks whether the given htlc parameters satisfy
3123
// the channel's amount and time lock constraints.
3124
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
3125
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
3126
        heightNow uint32, originalScid lnwire.ShortChannelID) *LinkError {
1,605✔
3127

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

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

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

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

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

2✔
3168
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
4✔
3169
                        return lnwire.NewExpiryTooSoon(*upd)
2✔
3170
                }
2✔
3171
                failure := l.createFailureWithUpdate(false, originalScid, cb)
2✔
3172
                return NewLinkError(failure)
2✔
3173
        }
3174

3175
        // Check absolute max delta.
3176
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
1,593✔
3177
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
1✔
3178
                        "the future: got %v, but maximum is %v", payHash[:],
1✔
3179
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
1✔
3180

1✔
3181
                return NewLinkError(&lnwire.FailExpiryTooFar{})
1✔
3182
        }
1✔
3183

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

3197
        return nil
1,590✔
3198
}
3199

3200
// Stats returns the statistics of channel link.
3201
//
3202
// NOTE: Part of the ChannelLink interface.
3203
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
24✔
3204
        snapshot := l.channel.StateSnapshot()
24✔
3205

24✔
3206
        return snapshot.ChannelCommitment.CommitHeight,
24✔
3207
                snapshot.TotalMSatSent,
24✔
3208
                snapshot.TotalMSatReceived
24✔
3209
}
24✔
3210

3211
// String returns the string representation of channel link.
3212
//
3213
// NOTE: Part of the ChannelLink interface.
3214
func (l *channelLink) String() string {
×
3215
        return l.channel.ChannelPoint().String()
×
3216
}
×
3217

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

1,523✔
3227
        return l.mailBox.AddPacket(pkt)
1,523✔
3228
}
1,523✔
3229

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

3244
        err := l.mailBox.AddMessage(message)
6,911✔
3245
        if err != nil {
6,911✔
3246
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
3247
        }
×
3248
}
3249

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

3✔
3255
        // We skip sending the UpdateFee message if the channel is not
3✔
3256
        // currently eligible to forward messages.
3✔
3257
        if !l.EligibleToUpdate() {
3✔
3258
                l.log.Debugf("skipping fee update for inactive channel")
×
3259
                return nil
×
3260
        }
×
3261

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

3271
        if thresholdExceeded {
3✔
3272
                return fmt.Errorf("link fee threshold exceeded")
×
3273
        }
×
3274

3275
        // First, we'll update the local fee on our commitment.
3276
        if err := l.channel.UpdateFee(feePerKw); err != nil {
3✔
3277
                return err
×
3278
        }
×
3279

3280
        // The fee passed the channel's validation checks, so we update the
3281
        // mailbox feerate.
3282
        l.mailBox.SetFeeRate(feePerKw)
3✔
3283

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

3293
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
3294
// after receiving a revocation from the remote party, and reprocesses them in
3295
// the context of the provided forwarding package. Any settles or fails that
3296
// have already been acknowledged in the forwarding package will not be sent to
3297
// the switch.
3298
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
2,225✔
3299
        if len(fwdPkg.SettleFails) == 0 {
3,701✔
3300
                return
1,476✔
3301
        }
1,476✔
3302

3303
        l.log.Debugf("settle-fail-filter: %v", fwdPkg.SettleFailFilter)
753✔
3304

753✔
3305
        var switchPackets []*htlcPacket
753✔
3306
        for i, update := range fwdPkg.SettleFails {
1,507✔
3307
                destRef := fwdPkg.DestRef(uint16(i))
754✔
3308

754✔
3309
                // Skip any settles or fails that have already been
754✔
3310
                // acknowledged by the incoming link that originated the
754✔
3311
                // forwarded Add.
754✔
3312
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
754✔
3313
                        continue
×
3314
                }
3315

3316
                // TODO(roasbeef): rework log entries to a shared
3317
                // interface.
3318

3319
                switch msg := update.UpdateMsg.(type) {
754✔
3320
                // A settle for an HTLC we previously forwarded HTLC has been
3321
                // received. So we'll forward the HTLC to the switch which will
3322
                // handle propagating the settle to the prior hop.
3323
                case *lnwire.UpdateFulfillHTLC:
631✔
3324
                        // If hodl.SettleIncoming is requested, we will not
631✔
3325
                        // forward the SETTLE to the switch and will not signal
631✔
3326
                        // a free slot on the commitment transaction.
631✔
3327
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
631✔
3328
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
3329
                                continue
×
3330
                        }
3331

3332
                        settlePacket := &htlcPacket{
631✔
3333
                                outgoingChanID: l.ShortChanID(),
631✔
3334
                                outgoingHTLCID: msg.ID,
631✔
3335
                                destRef:        &destRef,
631✔
3336
                                htlc:           msg,
631✔
3337
                        }
631✔
3338

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

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

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

127✔
3368
                        l.log.Debugf("Failed to send HTLC with ID=%d", msg.ID)
127✔
3369

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

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

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

3395
// processRemoteAdds serially processes each of the Add payment descriptors
3396
// which have been "locked-in" by receiving a revocation from the remote party.
3397
// The forwarding package provided instructs how to process this batch,
3398
// indicating whether this is the first time these Adds are being processed, or
3399
// whether we are reprocessing as a result of a failure or restart. Adds that
3400
// have already been acknowledged in the forwarding package will be ignored.
3401
//
3402
//nolint:funlen
3403
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
2,228✔
3404
        l.log.Tracef("processing %d remote adds for height %d",
2,228✔
3405
                len(fwdPkg.Adds), fwdPkg.Height)
2,228✔
3406

2,228✔
3407
        decodeReqs := make(
2,228✔
3408
                []hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds),
2,228✔
3409
        )
2,228✔
3410
        for _, update := range fwdPkg.Adds {
3,722✔
3411
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
2,988✔
3412
                        // Before adding the new htlc to the state machine,
1,494✔
3413
                        // parse the onion object in order to obtain the
1,494✔
3414
                        // routing information with DecodeHopIterator function
1,494✔
3415
                        // which process the Sphinx packet.
1,494✔
3416
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
1,494✔
3417

1,494✔
3418
                        req := hop.DecodeHopIteratorRequest{
1,494✔
3419
                                OnionReader:    onionReader,
1,494✔
3420
                                RHash:          msg.PaymentHash[:],
1,494✔
3421
                                IncomingCltv:   msg.Expiry,
1,494✔
3422
                                IncomingAmount: msg.Amount,
1,494✔
3423
                                BlindingPoint:  msg.BlindingPoint,
1,494✔
3424
                        }
1,494✔
3425

1,494✔
3426
                        decodeReqs = append(decodeReqs, req)
1,494✔
3427
                }
1,494✔
3428
        }
3429

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

3443
        var switchPackets []*htlcPacket
2,228✔
3444

2,228✔
3445
        for i, update := range fwdPkg.Adds {
3,722✔
3446
                idx := uint16(i)
1,494✔
3447

1,494✔
3448
                //nolint:forcetypeassert
1,494✔
3449
                add := *update.UpdateMsg.(*lnwire.UpdateAddHTLC)
1,494✔
3450
                sourceRef := fwdPkg.SourceRef(idx)
1,494✔
3451

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

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

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

3469
                // Before adding the new htlc to the state machine, parse the
3470
                // onion object in order to obtain the routing information with
3471
                // DecodeHopIterator function which process the Sphinx packet.
3472
                chanIterator, failureCode := decodeResps[i].Result()
1,494✔
3473
                if failureCode != lnwire.CodeNone {
1,500✔
3474
                        // If we're unable to process the onion blob then we
6✔
3475
                        // should send the malformed htlc error to payment
6✔
3476
                        // sender.
6✔
3477
                        l.sendMalformedHTLCError(
6✔
3478
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
6✔
3479
                        )
6✔
3480

6✔
3481
                        l.log.Errorf("unable to decode onion hop "+
6✔
3482
                                "iterator: %v", failureCode)
6✔
3483
                        continue
6✔
3484
                }
3485

3486
                heightNow := l.cfg.BestHeight()
1,492✔
3487

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

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

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

×
3520
                                // We can't process this htlc, send back
×
3521
                                // malformed.
×
3522
                                l.sendMalformedHTLCError(
×
3523
                                        add.ID, failureCode, add.OnionBlob,
×
3524
                                        &sourceRef,
×
3525
                                )
×
3526

×
3527
                                continue
×
3528
                        }
3529

3530
                        // TODO: currently none of the test unit infrastructure
3531
                        // is setup to handle TLV payloads, so testing this
3532
                        // would require implementing a separate mock iterator
3533
                        // for TLV payloads that also supports injecting invalid
3534
                        // payloads. Deferring this non-trival effort till a
3535
                        // later date
3536
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
4✔
3537

4✔
3538
                        l.sendHTLCError(
4✔
3539
                                add, sourceRef, NewLinkError(failure),
4✔
3540
                                obfuscator, false,
4✔
3541
                        )
4✔
3542

4✔
3543
                        l.log.Errorf("unable to decode forwarding "+
4✔
3544
                                "instructions: %v", pldErr)
4✔
3545

4✔
3546
                        continue
4✔
3547
                }
3548

3549
                // Retrieve onion obfuscator from onion blob in order to
3550
                // produce initial obfuscation of the onion failureCode.
3551
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
1,492✔
3552
                        l.cfg.ExtractErrorEncrypter,
1,492✔
3553
                        routeRole == hop.RouteRoleIntroduction,
1,492✔
3554
                )
1,492✔
3555
                if failureCode != lnwire.CodeNone {
1,493✔
3556
                        // If we're unable to process the onion blob than we
1✔
3557
                        // should send the malformed htlc error to payment
1✔
3558
                        // sender.
1✔
3559
                        l.sendMalformedHTLCError(
1✔
3560
                                add.ID, failureCode, add.OnionBlob,
1✔
3561
                                &sourceRef,
1✔
3562
                        )
1✔
3563

1✔
3564
                        l.log.Errorf("unable to decode onion "+
1✔
3565
                                "obfuscator: %v", failureCode)
1✔
3566

1✔
3567
                        continue
1✔
3568
                }
3569

3570
                fwdInfo := pld.ForwardingInfo()
1,491✔
3571

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

4✔
3579
                        failure := lnwire.NewInvalidBlinding(
4✔
3580
                                fn.Some(add.OnionBlob),
4✔
3581
                        )
4✔
3582

4✔
3583
                        l.sendHTLCError(
4✔
3584
                                add, sourceRef, NewLinkError(failure),
4✔
3585
                                obfuscator, false,
4✔
3586
                        )
4✔
3587

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

4✔
3592
                        continue
4✔
3593
                }
3594

3595
                switch fwdInfo.NextHop {
1,491✔
3596
                case hop.Exit:
1,455✔
3597
                        err := l.processExitHop(
1,455✔
3598
                                add, sourceRef, obfuscator, fwdInfo,
1,455✔
3599
                                heightNow, pld,
1,455✔
3600
                        )
1,455✔
3601
                        if err != nil {
1,459✔
3602
                                l.failf(LinkFailureError{
4✔
3603
                                        code: ErrInternalError,
4✔
3604
                                }, err.Error()) //nolint
4✔
3605

4✔
3606
                                return
4✔
3607
                        }
4✔
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✔
3616
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
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✔
3629
                                        break
×
3630
                                }
3631

3632
                                // Otherwise, it was already processed, we can
3633
                                // can collect it and continue.
3634
                                outgoingAdd := &lnwire.UpdateAddHTLC{
4✔
3635
                                        Expiry:        fwdInfo.OutgoingCTLV,
4✔
3636
                                        Amount:        fwdInfo.AmountToForward,
4✔
3637
                                        PaymentHash:   add.PaymentHash,
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(
4✔
3645
                                        outgoingAdd.OnionBlob[0:0],
4✔
3646
                                )
4✔
3647

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

4✔
3653
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
4✔
3654

4✔
3655
                                //nolint:lll
4✔
3656
                                updatePacket := &htlcPacket{
4✔
3657
                                        incomingChanID:       l.ShortChanID(),
4✔
3658
                                        incomingHTLCID:       add.ID,
4✔
3659
                                        outgoingChanID:       fwdInfo.NextHop,
4✔
3660
                                        sourceRef:            &sourceRef,
4✔
3661
                                        incomingAmount:       add.Amount,
4✔
3662
                                        amount:               outgoingAdd.Amount,
4✔
3663
                                        htlc:                 outgoingAdd,
4✔
3664
                                        obfuscator:           obfuscator,
4✔
3665
                                        incomingTimeout:      add.Expiry,
4✔
3666
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
4✔
3667
                                        inOnionCustomRecords: pld.CustomRecords(),
4✔
3668
                                        inboundFee:           inboundFee,
4✔
3669
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
4✔
3670
                                }
4✔
3671
                                switchPackets = append(
4✔
3672
                                        switchPackets, updatePacket,
4✔
3673
                                )
4✔
3674

4✔
3675
                                continue
4✔
3676
                        }
3677

3678
                        // TODO(roasbeef): ensure don't accept outrageous
3679
                        // timeout for htlc
3680

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

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

×
3700
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:lll
×
3701
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
3702
                                }
×
3703

3704
                                failure := l.createFailureWithUpdate(
×
3705
                                        true, hop.Source, cb,
×
3706
                                )
×
3707

×
3708
                                l.sendHTLCError(
×
3709
                                        add, sourceRef, NewLinkError(failure),
×
3710
                                        obfuscator, false,
×
3711
                                )
×
3712
                                continue
×
3713
                        }
3714

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

40✔
3726
                                //nolint:lll
40✔
3727
                                updatePacket := &htlcPacket{
40✔
3728
                                        incomingChanID:       l.ShortChanID(),
40✔
3729
                                        incomingHTLCID:       add.ID,
40✔
3730
                                        outgoingChanID:       fwdInfo.NextHop,
40✔
3731
                                        sourceRef:            &sourceRef,
40✔
3732
                                        incomingAmount:       add.Amount,
40✔
3733
                                        amount:               addMsg.Amount,
40✔
3734
                                        htlc:                 addMsg,
40✔
3735
                                        obfuscator:           obfuscator,
40✔
3736
                                        incomingTimeout:      add.Expiry,
40✔
3737
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
40✔
3738
                                        inOnionCustomRecords: pld.CustomRecords(),
40✔
3739
                                        inboundFee:           inboundFee,
40✔
3740
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
40✔
3741
                                }
40✔
3742

40✔
3743
                                fwdPkg.FwdFilter.Set(idx)
40✔
3744
                                switchPackets = append(switchPackets,
40✔
3745
                                        updatePacket)
40✔
3746
                        }
40✔
3747
                }
3748
        }
3749

3750
        // Commit the htlcs we are intending to forward if this package has not
3751
        // been fully processed.
3752
        if fwdPkg.State == channeldb.FwdStateLockedIn {
4,453✔
3753
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
2,225✔
3754
                if err != nil {
2,225✔
3755
                        l.failf(LinkFailureError{code: ErrInternalError},
×
3756
                                "unable to set fwd filter: %v", err)
×
3757
                        return
×
3758
                }
×
3759
        }
3760

3761
        if len(switchPackets) == 0 {
4,420✔
3762
                return
2,192✔
3763
        }
2,192✔
3764

3765
        replay := fwdPkg.State != channeldb.FwdStateLockedIn
40✔
3766

40✔
3767
        l.log.Debugf("forwarding %d packets to switch: replay=%v",
40✔
3768
                len(switchPackets), replay)
40✔
3769

40✔
3770
        // NOTE: This call is made synchronous so that we ensure all circuits
40✔
3771
        // are committed in the exact order that they are processed in the link.
40✔
3772
        // Failing to do this could cause reorderings/gaps in the range of
40✔
3773
        // opened circuits, which violates assumptions made by the circuit
40✔
3774
        // trimming.
40✔
3775
        l.forwardBatch(replay, switchPackets...)
40✔
3776
}
3777

3778
// processExitHop handles an htlc for which this link is the exit hop. It
3779
// returns a boolean indicating whether the commitment tx needs an update.
3780
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
3781
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
3782
        fwdInfo hop.ForwardingInfo, heightNow uint32,
3783
        payload invoices.Payload) error {
1,455✔
3784

1,455✔
3785
        // If hodl.ExitSettle is requested, we will not validate the final hop's
1,455✔
3786
        // ADD, nor will we settle the corresponding invoice or respond with the
1,455✔
3787
        // preimage.
1,455✔
3788
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
2,174✔
3789
                l.log.Warnf(hodl.ExitSettle.Warning())
719✔
3790

719✔
3791
                return nil
719✔
3792
        }
719✔
3793

3794
        // As we're the exit hop, we'll double check the hop-payload included in
3795
        // the HTLC to ensure that it was crafted correctly by the sender and
3796
        // is compatible with the HTLC we were extended.
3797
        //
3798
        // For a special case, if the fwdInfo doesn't have any blinded path
3799
        // information, and the incoming HTLC had special extra data, then
3800
        // we'll skip this amount check. The invoice acceptor will make sure we
3801
        // reject the HTLC if it's not containing the correct amount after
3802
        // examining the custom data.
3803
        hasBlindedPath := fwdInfo.NextBlinding.IsSome()
740✔
3804
        customHTLC := len(add.CustomRecords) > 0 && !hasBlindedPath
740✔
3805
        log.Tracef("Exit hop has_blinded_path=%v custom_htlc_bypass=%v",
740✔
3806
                hasBlindedPath, customHTLC)
740✔
3807

740✔
3808
        if !customHTLC && add.Amount < fwdInfo.AmountToForward {
840✔
3809
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
100✔
3810
                        "incompatible value: expected <=%v, got %v",
100✔
3811
                        add.PaymentHash, add.Amount, fwdInfo.AmountToForward)
100✔
3812

100✔
3813
                failure := NewLinkError(
100✔
3814
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
100✔
3815
                )
100✔
3816
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
100✔
3817

100✔
3818
                return nil
100✔
3819
        }
100✔
3820

3821
        // We'll also ensure that our time-lock value has been computed
3822
        // correctly.
3823
        if add.Expiry < fwdInfo.OutgoingCTLV {
641✔
3824
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
1✔
3825
                        "incompatible time-lock: expected <=%v, got %v",
1✔
3826
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
1✔
3827

1✔
3828
                failure := NewLinkError(
1✔
3829
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
1✔
3830
                )
1✔
3831

1✔
3832
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
1✔
3833

1✔
3834
                return nil
1✔
3835
        }
1✔
3836

3837
        // Notify the invoiceRegistry of the exit hop htlc. If we crash right
3838
        // after this, this code will be re-executed after restart. We will
3839
        // receive back a resolution event.
3840
        invoiceHash := lntypes.Hash(add.PaymentHash)
639✔
3841

639✔
3842
        circuitKey := models.CircuitKey{
639✔
3843
                ChanID: l.ShortChanID(),
639✔
3844
                HtlcID: add.ID,
639✔
3845
        }
639✔
3846

639✔
3847
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
639✔
3848
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
639✔
3849
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
639✔
3850
        )
639✔
3851
        if err != nil {
643✔
3852
                return err
4✔
3853
        }
4✔
3854

3855
        // Create a hodlHtlc struct and decide either resolved now or later.
3856
        htlc := hodlHtlc{
639✔
3857
                add:        add,
639✔
3858
                sourceRef:  sourceRef,
639✔
3859
                obfuscator: obfuscator,
639✔
3860
        }
639✔
3861

639✔
3862
        // If the event is nil, the invoice is being held, so we save payment
639✔
3863
        // descriptor for future reference.
639✔
3864
        if event == nil {
1,132✔
3865
                l.hodlMap[circuitKey] = htlc
493✔
3866
                return nil
493✔
3867
        }
493✔
3868

3869
        // Process the received resolution.
3870
        return l.processHtlcResolution(event, htlc)
150✔
3871
}
3872

3873
// settleHTLC settles the HTLC on the channel.
3874
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
3875
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
634✔
3876

634✔
3877
        hash := preimage.Hash()
634✔
3878

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

634✔
3881
        err := l.channel.SettleHTLC(
634✔
3882
                preimage, htlcIndex, &sourceRef, nil, nil,
634✔
3883
        )
634✔
3884
        if err != nil {
634✔
3885
                return fmt.Errorf("unable to settle htlc: %w", err)
×
3886
        }
×
3887

3888
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
3889
        // fake one before sending it to the peer.
3890
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
638✔
3891
                l.log.Warnf(hodl.BogusSettle.Warning())
4✔
3892
                preimage = [32]byte{}
4✔
3893
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
4✔
3894
        }
4✔
3895

3896
        // HTLC was successfully settled locally send notification about it
3897
        // remote peer.
3898
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
634✔
3899
                ChanID:          l.ChanID(),
634✔
3900
                ID:              htlcIndex,
634✔
3901
                PaymentPreimage: preimage,
634✔
3902
        })
634✔
3903

634✔
3904
        // Once we have successfully settled the htlc, notify a settle event.
634✔
3905
        l.cfg.HtlcNotifier.NotifySettleEvent(
634✔
3906
                HtlcKey{
634✔
3907
                        IncomingCircuit: models.CircuitKey{
634✔
3908
                                ChanID: l.ShortChanID(),
634✔
3909
                                HtlcID: htlcIndex,
634✔
3910
                        },
634✔
3911
                },
634✔
3912
                preimage,
634✔
3913
                HtlcEventTypeReceive,
634✔
3914
        )
634✔
3915

634✔
3916
        return nil
634✔
3917
}
3918

3919
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
3920
// err chan for the individual responses. This method is intended to be spawned
3921
// as a goroutine so the responses can be handled in the background.
3922
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
1,447✔
3923
        // Don't forward packets for which we already have a response in our
1,447✔
3924
        // mailbox. This could happen if a packet fails and is buffered in the
1,447✔
3925
        // mailbox, and the incoming link flaps.
1,447✔
3926
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
1,447✔
3927
        for _, pkt := range packets {
2,895✔
3928
                if l.mailBox.HasPacket(pkt.inKey()) {
1,452✔
3929
                        continue
4✔
3930
                }
3931

3932
                filteredPkts = append(filteredPkts, pkt)
1,448✔
3933
        }
3934

3935
        err := l.cfg.ForwardPackets(l.quit, replay, filteredPkts...)
1,447✔
3936
        if err != nil {
1,458✔
3937
                log.Errorf("Unhandled error while reforwarding htlc "+
11✔
3938
                        "settle/fail over htlcswitch: %v", err)
11✔
3939
        }
11✔
3940
}
3941

3942
// sendHTLCError functions cancels HTLC and send cancel message back to the
3943
// peer from which HTLC was received.
3944
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
3945
        sourceRef channeldb.AddRef, failure *LinkError,
3946
        e hop.ErrorEncrypter, isReceive bool) {
109✔
3947

109✔
3948
        reason, err := e.EncryptFirstHop(failure.WireMessage())
109✔
3949
        if err != nil {
109✔
3950
                l.log.Errorf("unable to obfuscate error: %v", err)
×
3951
                return
×
3952
        }
×
3953

3954
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
109✔
3955
        if err != nil {
109✔
3956
                l.log.Errorf("unable cancel htlc: %v", err)
×
3957
                return
×
3958
        }
×
3959

3960
        // Send the appropriate failure message depending on whether we're
3961
        // in a blinded route or not.
3962
        if err := l.sendIncomingHTLCFailureMsg(
109✔
3963
                add.ID, e, reason,
109✔
3964
        ); err != nil {
109✔
3965
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
3966
                return
×
3967
        }
×
3968

3969
        // Notify a link failure on our incoming link. Outgoing htlc information
3970
        // is not available at this point, because we have not decrypted the
3971
        // onion, so it is excluded.
3972
        var eventType HtlcEventType
109✔
3973
        if isReceive {
218✔
3974
                eventType = HtlcEventTypeReceive
109✔
3975
        } else {
113✔
3976
                eventType = HtlcEventTypeForward
4✔
3977
        }
4✔
3978

3979
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
109✔
3980
                HtlcKey{
109✔
3981
                        IncomingCircuit: models.CircuitKey{
109✔
3982
                                ChanID: l.ShortChanID(),
109✔
3983
                                HtlcID: add.ID,
109✔
3984
                        },
109✔
3985
                },
109✔
3986
                HtlcInfo{
109✔
3987
                        IncomingTimeLock: add.Expiry,
109✔
3988
                        IncomingAmt:      add.Amount,
109✔
3989
                },
109✔
3990
                eventType,
109✔
3991
                failure,
109✔
3992
                true,
109✔
3993
        )
109✔
3994
}
3995

3996
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
3997
// peer from which the HTLC was received. This function is primarily used to
3998
// handle the special requirements of route blinding, specifically:
3999
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
4000
// - Introduction nodes should return regular HTLC failure messages.
4001
//
4002
// It accepts the original opaque failure, which will be used in the case
4003
// that we're not part of a blinded route and an error encrypter that'll be
4004
// used if we are the introduction node and need to present an error as if
4005
// we're the failing party.
4006
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
4007
        e hop.ErrorEncrypter,
4008
        originalFailure lnwire.OpaqueReason) error {
125✔
4009

125✔
4010
        var msg lnwire.Message
125✔
4011
        switch {
125✔
4012
        // Our circuit's error encrypter will be nil if this was a locally
4013
        // initiated payment. We can only hit a blinded error for a locally
4014
        // initiated payment if we allow ourselves to be picked as the
4015
        // introduction node for our own payments and in that case we
4016
        // shouldn't reach this code. To prevent the HTLC getting stuck,
4017
        // we fail it back and log an error.
4018
        // code.
4019
        case e == nil:
×
4020
                msg = &lnwire.UpdateFailHTLC{
×
4021
                        ChanID: l.ChanID(),
×
4022
                        ID:     htlcIndex,
×
4023
                        Reason: originalFailure,
×
4024
                }
×
4025

×
4026
                l.log.Errorf("Unexpected blinded failure when "+
×
4027
                        "we are the sending node, incoming htlc: %v(%v)",
×
4028
                        l.ShortChanID(), htlcIndex)
×
4029

4030
        // For cleartext hops (ie, non-blinded/normal) we don't need any
4031
        // transformation on the error message and can just send the original.
4032
        case !e.Type().IsBlinded():
125✔
4033
                msg = &lnwire.UpdateFailHTLC{
125✔
4034
                        ChanID: l.ChanID(),
125✔
4035
                        ID:     htlcIndex,
125✔
4036
                        Reason: originalFailure,
125✔
4037
                }
125✔
4038

4039
        // When we're the introduction node, we need to convert the error to
4040
        // a UpdateFailHTLC.
4041
        case e.Type() == hop.EncrypterTypeIntroduction:
4✔
4042
                l.log.Debugf("Introduction blinded node switching out failure "+
4✔
4043
                        "error: %v", htlcIndex)
4✔
4044

4✔
4045
                // The specification does not require that we set the onion
4✔
4046
                // blob.
4✔
4047
                failureMsg := lnwire.NewInvalidBlinding(
4✔
4048
                        fn.None[[lnwire.OnionPacketSize]byte](),
4✔
4049
                )
4✔
4050
                reason, err := e.EncryptFirstHop(failureMsg)
4✔
4051
                if err != nil {
4✔
4052
                        return err
×
4053
                }
×
4054

4055
                msg = &lnwire.UpdateFailHTLC{
4✔
4056
                        ChanID: l.ChanID(),
4✔
4057
                        ID:     htlcIndex,
4✔
4058
                        Reason: reason,
4✔
4059
                }
4✔
4060

4061
        // If we are a relaying node, we need to switch out any error that
4062
        // we've received to a malformed HTLC error.
4063
        case e.Type() == hop.EncrypterTypeRelaying:
4✔
4064
                l.log.Debugf("Relaying blinded node switching out malformed "+
4✔
4065
                        "error: %v", htlcIndex)
4✔
4066

4✔
4067
                msg = &lnwire.UpdateFailMalformedHTLC{
4✔
4068
                        ChanID:      l.ChanID(),
4✔
4069
                        ID:          htlcIndex,
4✔
4070
                        FailureCode: lnwire.CodeInvalidBlinding,
4✔
4071
                }
4✔
4072

4073
        default:
×
4074
                return fmt.Errorf("unexpected encrypter: %d", e)
×
4075
        }
4076

4077
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
125✔
4078
                l.log.Warnf("Send update fail failed: %v", err)
×
4079
        }
×
4080

4081
        return nil
125✔
4082
}
4083

4084
// sendMalformedHTLCError helper function which sends the malformed HTLC update
4085
// to the payment sender.
4086
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
4087
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
4088
        sourceRef *channeldb.AddRef) {
7✔
4089

7✔
4090
        shaOnionBlob := sha256.Sum256(onionBlob[:])
7✔
4091
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
7✔
4092
        if err != nil {
7✔
4093
                l.log.Errorf("unable cancel htlc: %v", err)
×
4094
                return
×
4095
        }
×
4096

4097
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
7✔
4098
                ChanID:       l.ChanID(),
7✔
4099
                ID:           htlcIndex,
7✔
4100
                ShaOnionBlob: shaOnionBlob,
7✔
4101
                FailureCode:  code,
7✔
4102
        })
7✔
4103
}
4104

4105
// failf is a function which is used to encapsulate the action necessary for
4106
// properly failing the link. It takes a LinkFailureError, which will be passed
4107
// to the OnChannelFailure closure, in order for it to determine if we should
4108
// force close the channel, and if we should send an error message to the
4109
// remote peer.
4110
func (l *channelLink) failf(linkErr LinkFailureError, format string,
4111
        a ...interface{}) {
11✔
4112

11✔
4113
        reason := fmt.Errorf(format, a...)
11✔
4114

11✔
4115
        // Return if we have already notified about a failure.
11✔
4116
        if l.failed {
15✔
4117
                l.log.Warnf("ignoring link failure (%v), as link already "+
4✔
4118
                        "failed", reason)
4✔
4119
                return
4✔
4120
        }
4✔
4121

4122
        l.log.Errorf("failing link: %s with error: %v", reason, linkErr)
11✔
4123

11✔
4124
        // Set failed, such that we won't process any more updates, and notify
11✔
4125
        // the peer about the failure.
11✔
4126
        l.failed = true
11✔
4127
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
11✔
4128
}
4129

4130
// FundingCustomBlob returns the custom funding blob of the channel that this
4131
// link is associated with. The funding blob represents static information about
4132
// the channel that was created at channel funding time.
4133
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
4134
        if l.channel == nil {
×
4135
                return fn.None[tlv.Blob]()
×
4136
        }
×
4137

4138
        if l.channel.State() == nil {
×
4139
                return fn.None[tlv.Blob]()
×
4140
        }
×
4141

4142
        return l.channel.State().CustomBlob
×
4143
}
4144

4145
// CommitmentCustomBlob returns the custom blob of the current local commitment
4146
// of the channel that this link is associated with.
4147
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
4148
        if l.channel == nil {
×
4149
                return fn.None[tlv.Blob]()
×
4150
        }
×
4151

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