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

lightningnetwork / lnd / 12255867314

10 Dec 2024 12:12PM UTC coverage: 49.842% (+0.07%) from 49.773%
12255867314

Pull #9344

github

ellemouton
htlcswitch+go.mod: use updated fn.ContextGuard

This commit updates the fn dep to the version containing the updates to
the ContextGuard implementation. Only the htlcswitch/link uses the guard
at the moment so this is updated to make use of the new implementation.
Pull Request #9344: htlcswitch+go.mod: use updated fn.ContextGuard

40 of 54 new or added lines in 2 files covered. (74.07%)

31 existing lines in 8 files now uncovered.

100222 of 201080 relevant lines covered (49.84%)

2.07 hits per line

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

67.61
/htlcswitch/link.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

314
        // failed should be set to true in case a link error happens, making
315
        // sure we don't process any more updates.
316
        failed bool
317

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

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

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

337
        // channel is a lightning network channel to which we apply htlc
338
        // updates.
339
        channel *lnwallet.LightningChannel
340

341
        // cfg is a structure which carries all dependable fields/handlers
342
        // which may affect behaviour of the service.
343
        cfg ChannelLinkConfig
344

345
        // mailBox is the main interface between the outside world and the
346
        // link. All incoming messages will be sent over this mailBox. Messages
347
        // include new updates from our connected peer, and new packets to be
348
        // forwarded sent by the switch.
349
        mailBox MailBox
350

351
        // upstream is a channel that new messages sent from the remote peer to
352
        // the local peer will be sent across.
353
        upstream chan lnwire.Message
354

355
        // downstream is a channel in which new multi-hop HTLC's to be
356
        // forwarded will be sent across. Messages from this channel are sent
357
        // by the HTLC switch.
358
        downstream chan *htlcPacket
359

360
        // updateFeeTimer is the timer responsible for updating the link's
361
        // commitment fee every time it fires.
362
        updateFeeTimer *time.Timer
363

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

370
        sync.RWMutex
371

372
        // hodlQueue is used to receive exit hop htlc resolutions from invoice
373
        // registry.
374
        hodlQueue *queue.ConcurrentQueue
375

376
        // hodlMap stores related htlc data for a circuit key. It allows
377
        // resolving those htlcs when we receive a message on hodlQueue.
378
        hodlMap map[models.CircuitKey]hodlHtlc
379

380
        // log is a link-specific logging instance.
381
        log btclog.Logger
382

383
        // isOutgoingAddBlocked tracks whether the channelLink can send an
384
        // UpdateAddHTLC.
385
        isOutgoingAddBlocked atomic.Bool
386

387
        // isIncomingAddBlocked tracks whether the channelLink can receive an
388
        // UpdateAddHTLC.
389
        isIncomingAddBlocked atomic.Bool
390

391
        // flushHooks is a hookMap that is triggered when we reach a channel
392
        // state with no live HTLCs.
393
        flushHooks hookMap
394

395
        // outgoingCommitHooks is a hookMap that is triggered after we send our
396
        // next CommitSig.
397
        outgoingCommitHooks hookMap
398

399
        // incomingCommitHooks is a hookMap that is triggered after we receive
400
        // our next CommitSig.
401
        incomingCommitHooks hookMap
402

403
        // quiescer is the state machine that tracks where this channel is with
404
        // respect to the quiescence protocol.
405
        quiescer Quiescer
406

407
        // quiescenceReqs is a queue of requests to quiesce this link. The
408
        // members of the queue are send-only channels we should call back with
409
        // the result.
410
        quiescenceReqs chan StfuReq
411

412
        // cg is a helper that encapsulates a wait group and quit channel and
413
        // allows contexts that either block or cancel on those depending on
414
        // the use case.
415
        cg *fn.ContextGuard
416
}
417

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

426
        // transient is a map of hooks that are only called the next time invoke
427
        // is called. These hooks are deleted during invoke.
428
        transient map[uint64]func()
429

430
        // newTransients is a channel that we use to accept new hooks into the
431
        // hookMap.
432
        newTransients chan func()
433
}
434

435
// newHookMap initializes a new empty hookMap.
436
func newHookMap() hookMap {
4✔
437
        return hookMap{
4✔
438
                allocIdx:      atomic.Uint64{},
4✔
439
                transient:     make(map[uint64]func()),
4✔
440
                newTransients: make(chan func()),
4✔
441
        }
4✔
442
}
4✔
443

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

4✔
455
        return hookID
4✔
456
}
457

458
// invoke is used on a hook map to call all the registered hooks and then clear
459
// out the transient hooks so they are not called again.
460
func (m *hookMap) invoke() {
4✔
461
        for _, hook := range m.transient {
8✔
462
                hook()
4✔
463
        }
4✔
464

465
        m.transient = make(map[uint64]func())
4✔
466
}
467

468
// hodlHtlc contains htlc data that is required for resolution.
469
type hodlHtlc struct {
470
        add        lnwire.UpdateAddHTLC
471
        sourceRef  channeldb.AddRef
472
        obfuscator hop.ErrorEncrypter
473
}
474

475
// NewChannelLink creates a new instance of a ChannelLink given a configuration
476
// and active channel that will be used to verify/apply updates to.
477
func NewChannelLink(cfg ChannelLinkConfig,
478
        channel *lnwallet.LightningChannel) ChannelLink {
4✔
479

4✔
480
        logPrefix := fmt.Sprintf("ChannelLink(%v):", channel.ChannelPoint())
4✔
481

4✔
482
        // If the max fee exposure isn't set, use the default.
4✔
483
        if cfg.MaxFeeExposure == 0 {
4✔
484
                cfg.MaxFeeExposure = DefaultMaxFeeExposure
×
485
        }
×
486

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

506
        quiescenceReqs := make(
4✔
507
                chan fn.Req[fn.Unit, fn.Result[lntypes.ChannelParty]], 1,
4✔
508
        )
4✔
509

4✔
510
        return &channelLink{
4✔
511
                cfg:                 cfg,
4✔
512
                channel:             channel,
4✔
513
                hodlMap:             make(map[models.CircuitKey]hodlHtlc),
4✔
514
                hodlQueue:           queue.NewConcurrentQueue(10),
4✔
515
                log:                 log.WithPrefix(logPrefix),
4✔
516
                flushHooks:          newHookMap(),
4✔
517
                outgoingCommitHooks: newHookMap(),
4✔
518
                incomingCommitHooks: newHookMap(),
4✔
519
                quiescer:            qsm,
4✔
520
                quiescenceReqs:      quiescenceReqs,
4✔
521
                cg:                  fn.NewContextGuard(),
4✔
522
        }
4✔
523
}
524

525
// A compile time check to ensure channelLink implements the ChannelLink
526
// interface.
527
var _ ChannelLink = (*channelLink)(nil)
528

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

540
        l.log.Info("starting")
4✔
541

4✔
542
        // If the config supplied watchtower client, ensure the channel is
4✔
543
        // registered before trying to use it during operation.
4✔
544
        if l.cfg.TowerClient != nil {
8✔
545
                err := l.cfg.TowerClient.RegisterChannel(
4✔
546
                        l.ChanID(), l.channel.State().ChanType,
4✔
547
                )
4✔
548
                if err != nil {
4✔
549
                        return err
×
550
                }
×
551
        }
552

553
        l.mailBox.ResetMessages()
4✔
554
        l.hodlQueue.Start()
4✔
555

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

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

581
                // Since the link is live, before we start the link we'll update
582
                // the ChainArbitrator with the set of new channel signals for
583
                // this channel.
584
                //
585
                // TODO(roasbeef): split goroutines within channel arb to avoid
586
                go func() {
8✔
587
                        signals := &contractcourt.ContractSignals{
4✔
588
                                ShortChanID: l.channel.ShortChanID(),
4✔
589
                        }
4✔
590

4✔
591
                        err := l.cfg.UpdateContractSignals(signals)
4✔
592
                        if err != nil {
4✔
593
                                l.log.Errorf("unable to update signals")
×
594
                        }
×
595
                }()
596
        }
597

598
        l.updateFeeTimer = time.NewTimer(l.randomFeeUpdateTimeout())
4✔
599

4✔
600
        l.cg.WgAdd(1)
4✔
601
        go l.htlcManager(context.TODO())
4✔
602

4✔
603
        return nil
4✔
604
}
605

606
// Stop gracefully stops all active helper goroutines, then waits until they've
607
// exited.
608
//
609
// NOTE: Part of the ChannelLink interface.
610
func (l *channelLink) Stop() {
4✔
611
        if !atomic.CompareAndSwapInt32(&l.shutdown, 0, 1) {
4✔
612
                l.log.Warn("already stopped")
×
613
                return
×
614
        }
×
615

616
        l.log.Info("stopping")
4✔
617

4✔
618
        // As the link is stopping, we are no longer interested in htlc
4✔
619
        // resolutions coming from the invoice registry.
4✔
620
        l.cfg.Registry.HodlUnsubscribeAll(l.hodlQueue.ChanIn())
4✔
621

4✔
622
        if l.cfg.ChainEvents.Cancel != nil {
8✔
623
                l.cfg.ChainEvents.Cancel()
4✔
624
        }
4✔
625

626
        // Ensure the channel for the timer is drained.
627
        if l.updateFeeTimer != nil {
8✔
628
                if !l.updateFeeTimer.Stop() {
4✔
629
                        select {
×
630
                        case <-l.updateFeeTimer.C:
×
631
                        default:
×
632
                        }
633
                }
634
        }
635

636
        if l.hodlQueue != nil {
8✔
637
                l.hodlQueue.Stop()
4✔
638
        }
4✔
639

640
        l.cg.Quit()
4✔
641
        l.cg.WgWait()
4✔
642

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

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

663
// WaitForShutdown blocks until the link finishes shutting down, which includes
664
// termination of all dependent goroutines.
665
func (l *channelLink) WaitForShutdown() {
×
NEW
666
        l.cg.WgWait()
×
667
}
×
668

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

4✔
679
        return l.eligibleToForward()
4✔
680
}
4✔
681

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

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

706
// EnableAdds sets the ChannelUpdateHandler state to allow UpdateAddHtlc's in
707
// the specified direction. It returns true if the state was changed and false
708
// if the desired state was already set before the method was called.
709
func (l *channelLink) EnableAdds(linkDirection LinkDirection) bool {
×
710
        if linkDirection == Outgoing {
×
711
                return l.isOutgoingAddBlocked.Swap(false)
×
712
        }
×
713

714
        return l.isIncomingAddBlocked.Swap(false)
×
715
}
716

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

725
        return !l.isIncomingAddBlocked.Swap(true)
4✔
726
}
727

728
// IsFlushing returns true when UpdateAddHtlc's are disabled in the direction of
729
// the argument.
730
func (l *channelLink) IsFlushing(linkDirection LinkDirection) bool {
4✔
731
        if linkDirection == Outgoing {
8✔
732
                return l.isOutgoingAddBlocked.Load()
4✔
733
        }
4✔
734

735
        return l.isIncomingAddBlocked.Load()
4✔
736
}
737

738
// OnFlushedOnce adds a hook that will be called the next time the channel
739
// state reaches zero htlcs. This hook will only ever be called once. If the
740
// channel state already has zero htlcs, then this will be called immediately.
741
func (l *channelLink) OnFlushedOnce(hook func()) {
4✔
742
        select {
4✔
743
        case l.flushHooks.newTransients <- hook:
4✔
NEW
744
        case <-l.cg.Done():
×
745
        }
746
}
747

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

4✔
755
        if direction == Outgoing {
8✔
756
                queue = l.outgoingCommitHooks.newTransients
4✔
757
        } else {
4✔
758
                queue = l.incomingCommitHooks.newTransients
×
759
        }
×
760

761
        select {
4✔
762
        case queue <- hook:
4✔
NEW
763
        case <-l.cg.Done():
×
764
        }
765
}
766

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

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

785
        return out
4✔
786
}
787

788
// isReestablished returns true if the link has successfully completed the
789
// channel reestablishment dance.
790
func (l *channelLink) isReestablished() bool {
4✔
791
        return atomic.LoadInt32(&l.reestablished) == 1
4✔
792
}
4✔
793

794
// markReestablished signals that the remote peer has successfully exchanged
795
// channel reestablish messages and that the channel is ready to process
796
// subsequent messages.
797
func (l *channelLink) markReestablished() {
4✔
798
        atomic.StoreInt32(&l.reestablished, 1)
4✔
799
}
4✔
800

801
// IsUnadvertised returns true if the underlying channel is unadvertised.
802
func (l *channelLink) IsUnadvertised() bool {
4✔
803
        state := l.channel.State()
4✔
804
        return state.ChannelFlags&lnwire.FFAnnounceChannel == 0
4✔
805
}
4✔
806

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

819
        l.log.Debugf("sampled fee rate for 3 block conf: %v sat/kw",
×
820
                int64(feePerKw))
×
821

×
822
        return feePerKw, nil
×
823
}
824

825
// shouldAdjustCommitFee returns true if we should update our commitment fee to
826
// match that of the network fee. We'll only update our commitment fee if the
827
// network fee is +/- 10% to our commitment fee or if our current commitment
828
// fee is below the minimum relay fee.
829
func shouldAdjustCommitFee(netFee, chanFee,
830
        minRelayFee chainfee.SatPerKWeight) bool {
×
831

×
832
        switch {
×
833
        // If the network fee is greater than our current commitment fee and
834
        // our current commitment fee is below the minimum relay fee then
835
        // we should switch to it no matter if it is less than a 10% increase.
836
        case netFee > chanFee && chanFee < minRelayFee:
×
837
                return true
×
838

839
        // If the network fee is greater than the commitment fee, then we'll
840
        // switch to it if it's at least 10% greater than the commit fee.
841
        case netFee > chanFee && netFee >= (chanFee+(chanFee*10)/100):
×
842
                return true
×
843

844
        // If the network fee is less than our commitment fee, then we'll
845
        // switch to it if it's at least 10% less than the commitment fee.
846
        case netFee < chanFee && netFee <= (chanFee-(chanFee*10)/100):
×
847
                return true
×
848

849
        // Otherwise, we won't modify our fee.
850
        default:
×
851
                return false
×
852
        }
853
}
854

855
// failCb is used to cut down on the argument verbosity.
856
type failCb func(update *lnwire.ChannelUpdate1) lnwire.FailureMessage
857

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

4✔
865
        // Determine which SCID to use in case we need to use aliases in the
4✔
866
        // ChannelUpdate.
4✔
867
        scid := outgoingScid
4✔
868
        if incoming {
4✔
869
                scid = l.ShortChanID()
×
870
        }
×
871

872
        // Try using the FailAliasUpdate function. If it returns nil, fallback
873
        // to the non-alias behavior.
874
        update := l.cfg.FailAliasUpdate(scid, incoming)
4✔
875
        if update == nil {
8✔
876
                // Fallback to the non-alias behavior.
4✔
877
                var err error
4✔
878
                update, err = l.cfg.FetchLastChannelUpdate(l.ShortChanID())
4✔
879
                if err != nil {
4✔
880
                        return &lnwire.FailTemporaryNodeFailure{}
×
881
                }
×
882
        }
883

884
        return cb(update)
4✔
885
}
886

887
// syncChanState attempts to synchronize channel states with the remote party.
888
// This method is to be called upon reconnection after the initial funding
889
// flow. We'll compare out commitment chains with the remote party, and re-send
890
// either a danging commit signature, a revocation, or both.
891
func (l *channelLink) syncChanStates(ctx context.Context) error {
4✔
892
        chanState := l.channel.State()
4✔
893

4✔
894
        l.log.Infof("Attempting to re-synchronize channel: %v", chanState)
4✔
895

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

909
        var msgsToReSend []lnwire.Message
4✔
910

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

4✔
918
                remoteChanSyncMsg, ok := msg.(*lnwire.ChannelReestablish)
4✔
919
                if !ok {
4✔
920
                        return fmt.Errorf("first message sent to sync "+
×
921
                                "should be ChannelReestablish, instead "+
×
922
                                "received: %T", msg)
×
923
                }
×
924

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

4✔
934
                        l.log.Infof("resending ChannelReady message to peer")
4✔
935

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

942
                        channelReadyMsg := lnwire.NewChannelReady(
4✔
943
                                l.ChanID(), nextRevocation,
4✔
944
                        )
4✔
945

4✔
946
                        // If this is a taproot channel, then we'll send the
4✔
947
                        // very same nonce that we sent above, as they should
4✔
948
                        // take the latest verification nonce we send.
4✔
949
                        if chanState.ChanType.IsTaproot() {
8✔
950
                                //nolint:ll
4✔
951
                                channelReadyMsg.NextLocalNonce = localChanSyncMsg.LocalNonce
4✔
952
                        }
4✔
953

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

969
                                // getAliases returns a copy of the alias slice
970
                                // so it is ok to use a pointer to the first
971
                                // entry.
972
                                channelReadyMsg.AliasScid = &aliases[0]
4✔
973
                        }
974

975
                        err = l.cfg.Peer.SendMessage(false, channelReadyMsg)
4✔
976
                        if err != nil {
4✔
977
                                return fmt.Errorf("unable to re-send "+
×
978
                                        "ChannelReady: %v", err)
×
979
                        }
×
980
                }
981

982
                // In any case, we'll then process their ChanSync message.
983
                l.log.Info("received re-establishment message from remote side")
4✔
984

4✔
985
                var (
4✔
986
                        openedCircuits []CircuitKey
4✔
987
                        closedCircuits []CircuitKey
4✔
988
                )
4✔
989

4✔
990
                // We've just received a ChanSync message from the remote
4✔
991
                // party, so we'll process the message  in order to determine
4✔
992
                // if we need to re-transmit any messages to the remote party.
4✔
993
                ctx, cancel := l.cg.WithCtx(ctx)
4✔
994
                defer cancel()
4✔
995
                msgsToReSend, openedCircuits, closedCircuits, err =
4✔
996
                        l.channel.ProcessChanSyncMsg(ctx, remoteChanSyncMsg)
4✔
997
                if err != nil {
8✔
998
                        return err
4✔
999
                }
4✔
1000

1001
                // Repopulate any identifiers for circuits that may have been
1002
                // opened or unclosed. This may happen if we needed to
1003
                // retransmit a commitment signature message.
1004
                l.openedCircuits = openedCircuits
4✔
1005
                l.closedCircuits = closedCircuits
4✔
1006

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

1013
                if len(msgsToReSend) > 0 {
4✔
1014
                        l.log.Infof("sending %v updates to synchronize the "+
×
1015
                                "state", len(msgsToReSend))
×
1016
                }
×
1017

1018
                // If we have any messages to retransmit, we'll do so
1019
                // immediately so we return to a synchronized state as soon as
1020
                // possible.
1021
                for _, msg := range msgsToReSend {
4✔
1022
                        l.cfg.Peer.SendMessage(false, msg)
×
1023
                }
×
1024

1025
        case <-l.cg.Done():
4✔
1026
                return ErrLinkShuttingDown
4✔
1027
        }
1028

1029
        return nil
4✔
1030
}
1031

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

1043
        l.log.Debugf("loaded %d fwd pks", len(fwdPkgs))
4✔
1044

4✔
1045
        for _, fwdPkg := range fwdPkgs {
8✔
1046
                if err := l.resolveFwdPkg(fwdPkg); err != nil {
4✔
UNCOV
1047
                        return err
×
UNCOV
1048
                }
×
1049
        }
1050

1051
        // If any of our reprocessing steps require an update to the commitment
1052
        // txn, we initiate a state transition to capture all relevant changes.
1053
        if l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote) > 0 {
8✔
1054
                return l.updateCommitTx(ctx)
4✔
1055
        }
4✔
1056

1057
        return nil
4✔
1058
}
1059

1060
// resolveFwdPkg interprets the FwdState of the provided package, either
1061
// reprocesses any outstanding htlcs in the package, or performs garbage
1062
// collection on the package.
1063
func (l *channelLink) resolveFwdPkg(fwdPkg *channeldb.FwdPkg) error {
4✔
1064
        // Remove any completed packages to clear up space.
4✔
1065
        if fwdPkg.State == channeldb.FwdStateCompleted {
8✔
1066
                l.log.Debugf("removing completed fwd pkg for height=%d",
4✔
1067
                        fwdPkg.Height)
4✔
1068

4✔
1069
                err := l.channel.RemoveFwdPkgs(fwdPkg.Height)
4✔
1070
                if err != nil {
4✔
UNCOV
1071
                        l.log.Errorf("unable to remove fwd pkg for height=%d: "+
×
UNCOV
1072
                                "%v", fwdPkg.Height, err)
×
UNCOV
1073
                        return err
×
UNCOV
1074
                }
×
1075
        }
1076

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

1083
        // If the package is fully acked but not completed, it must still have
1084
        // settles and fails to propagate.
1085
        if !fwdPkg.SettleFailFilter.IsFull() {
8✔
1086
                l.processRemoteSettleFails(fwdPkg)
4✔
1087
        }
4✔
1088

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

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

1105
        return nil
4✔
1106
}
1107

1108
// fwdPkgGarbager periodically reads all forwarding packages from disk and
1109
// removes those that can be discarded. It is safe to do this entirely in the
1110
// background, since all state is coordinated on disk. This also ensures the
1111
// link can continue to process messages and interleave database accesses.
1112
//
1113
// NOTE: This MUST be run as a goroutine.
1114
func (l *channelLink) fwdPkgGarbager() {
4✔
1115
        defer l.cg.WgDone()
4✔
1116

4✔
1117
        l.cfg.FwdPkgGCTicker.Resume()
4✔
1118
        defer l.cfg.FwdPkgGCTicker.Stop()
4✔
1119

4✔
1120
        if err := l.loadAndRemove(); err != nil {
4✔
1121
                l.log.Warnf("unable to run initial fwd pkgs gc: %v", err)
×
1122
        }
×
1123

1124
        for {
8✔
1125
                select {
4✔
1126
                case <-l.cfg.FwdPkgGCTicker.Ticks():
×
1127
                        if err := l.loadAndRemove(); err != nil {
×
1128
                                l.log.Warnf("unable to remove fwd pkgs: %v",
×
1129
                                        err)
×
1130
                                continue
×
1131
                        }
1132
                case <-l.cg.Done():
4✔
1133
                        return
4✔
1134
                }
1135
        }
1136
}
1137

1138
// loadAndRemove loads all the channels forwarding packages and determines if
1139
// they can be removed. It is called once before the FwdPkgGCTicker ticks so that
1140
// a longer tick interval can be used.
1141
func (l *channelLink) loadAndRemove() error {
4✔
1142
        fwdPkgs, err := l.channel.LoadFwdPkgs()
4✔
1143
        if err != nil {
4✔
1144
                return err
×
1145
        }
×
1146

1147
        var removeHeights []uint64
4✔
1148
        for _, fwdPkg := range fwdPkgs {
8✔
1149
                if fwdPkg.State != channeldb.FwdStateCompleted {
8✔
1150
                        continue
4✔
1151
                }
1152

1153
                removeHeights = append(removeHeights, fwdPkg.Height)
4✔
1154
        }
1155

1156
        // If removeHeights is empty, return early so we don't use a db
1157
        // transaction.
1158
        if len(removeHeights) == 0 {
8✔
1159
                return nil
4✔
1160
        }
4✔
1161

1162
        return l.channel.RemoveFwdPkgs(removeHeights...)
4✔
1163
}
1164

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

4✔
1170
        var errDataLoss *lnwallet.ErrCommitSyncLocalDataLoss
4✔
1171

4✔
1172
        switch {
4✔
1173
        case errors.Is(err, ErrLinkShuttingDown):
4✔
1174
                l.log.Debugf("unable to sync channel states, link is " +
4✔
1175
                        "shutting down")
4✔
1176
                return
4✔
1177

1178
        // We failed syncing the commit chains, probably because the remote has
1179
        // lost state. We should force close the channel.
1180
        case errors.Is(err, lnwallet.ErrCommitSyncRemoteDataLoss):
4✔
1181
                fallthrough
4✔
1182

1183
        // The remote sent us an invalid last commit secret, we should force
1184
        // close the channel.
1185
        // TODO(halseth): and permanently ban the peer?
1186
        case errors.Is(err, lnwallet.ErrInvalidLastCommitSecret):
4✔
1187
                fallthrough
4✔
1188

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

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

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

1229
        // Other, unspecified error.
1230
        default:
×
1231
        }
1232

1233
        l.failf(
4✔
1234
                LinkFailureError{
4✔
1235
                        code:          ErrRecoveryError,
4✔
1236
                        FailureAction: LinkFailureForceNone,
4✔
1237
                },
4✔
1238
                "unable to synchronize channel states: %v", err,
4✔
1239
        )
4✔
1240
}
1241

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

1259
        l.log.Infof("HTLC manager started, bandwidth=%v", l.Bandwidth())
4✔
1260

4✔
1261
        // Notify any clients that the link is now in the switch via an
4✔
1262
        // ActiveLinkEvent. We'll also defer an inactive link notification for
4✔
1263
        // when the link exits to ensure that every active notification is
4✔
1264
        // matched by an inactive one.
4✔
1265
        l.cfg.NotifyActiveLink(l.ChannelPoint())
4✔
1266
        defer l.cfg.NotifyInactiveLinkEvent(l.ChannelPoint())
4✔
1267

4✔
1268
        // TODO(roasbeef): need to call wipe chan whenever D/C?
4✔
1269

4✔
1270
        // If this isn't the first time that this channel link has been
4✔
1271
        // created, then we'll need to check to see if we need to
4✔
1272
        // re-synchronize state with the remote peer. settledHtlcs is a map of
4✔
1273
        // HTLC's that we re-settled as part of the channel state sync.
4✔
1274
        if l.cfg.SyncStates {
8✔
1275
                err := l.syncChanStates(ctx)
4✔
1276
                if err != nil {
8✔
1277
                        l.handleChanSyncErr(err)
4✔
1278
                        return
4✔
1279
                }
4✔
1280
        }
1281

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

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

1301
        // We've successfully reestablished the channel, mark it as such to
1302
        // allow the switch to forward HTLCs in the outbound direction.
1303
        l.markReestablished()
4✔
1304

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

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

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

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

1338
                // A non-nil error was encountered, send an Error message to
1339
                // the peer.
1340
                default:
1✔
1341
                        l.failf(LinkFailureError{code: ErrInternalError},
1✔
1342
                                "unable to resolve fwd pkgs: %v", err)
1✔
1343
                        return
1✔
1344
                }
1345

1346
                // With our link's in-memory state fully reconstructed, spawn a
1347
                // goroutine to manage the reclamation of disk space occupied by
1348
                // completed forwarding packages.
1349
                l.cg.WgAdd(1)
4✔
1350
                go l.fwdPkgGarbager()
4✔
1351
        }
1352

1353
        for {
8✔
1354
                // We must always check if we failed at some point processing
4✔
1355
                // the last update before processing the next.
4✔
1356
                if l.failed {
8✔
1357
                        l.log.Errorf("link failed, exiting htlcManager")
4✔
1358
                        return
4✔
1359
                }
4✔
1360

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

1380
                select {
4✔
1381
                // We have a new hook that needs to be run when we reach a clean
1382
                // channel state.
1383
                case hook := <-l.flushHooks.newTransients:
4✔
1384
                        if l.channel.IsChannelClean() {
8✔
1385
                                hook()
4✔
1386
                        } else {
8✔
1387
                                l.flushHooks.alloc(hook)
4✔
1388
                        }
4✔
1389

1390
                // We have a new hook that needs to be run when we have
1391
                // committed all of our updates.
1392
                case hook := <-l.outgoingCommitHooks.newTransients:
4✔
1393
                        if !l.channel.OweCommitment() {
8✔
1394
                                hook()
4✔
1395
                        } else {
4✔
1396
                                l.outgoingCommitHooks.alloc(hook)
×
1397
                        }
×
1398

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

1408
                // Our update fee timer has fired, so we'll check the network
1409
                // fee to see if we should adjust our commitment fee.
1410
                case <-l.updateFeeTimer.C:
×
1411
                        l.updateFeeTimer.Reset(l.randomFeeUpdateTimeout())
×
1412

×
1413
                        // If we're not the initiator of the channel, don't we
×
1414
                        // don't control the fees, so we can ignore this.
×
1415
                        if !l.channel.IsInitiator() {
×
1416
                                continue
×
1417
                        }
1418

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

1429
                        minRelayFee := l.cfg.FeeEstimator.RelayFeePerKW()
×
1430

×
1431
                        newCommitFee := l.channel.IdealCommitFeeRate(
×
1432
                                netFee, minRelayFee,
×
1433
                                l.cfg.MaxAnchorsCommitFeeRate,
×
1434
                                l.cfg.MaxFeeAllocation,
×
1435
                        )
×
1436

×
1437
                        // We determine if we should adjust the commitment fee
×
1438
                        // based on the current commitment fee, the suggested
×
1439
                        // new commitment fee and the current minimum relay fee
×
1440
                        // rate.
×
1441
                        commitFee := l.channel.CommitFeeRate()
×
1442
                        if !shouldAdjustCommitFee(
×
1443
                                newCommitFee, commitFee, minRelayFee,
×
1444
                        ) {
×
1445

×
1446
                                continue
×
1447
                        }
1448

1449
                        // If we do, then we'll send a new UpdateFee message to
1450
                        // the remote party, to be locked in with a new update.
NEW
1451
                        err = l.updateChannelFee(ctx, newCommitFee)
×
NEW
1452
                        if err != nil {
×
1453
                                l.log.Errorf("unable to update fee rate: %v",
×
1454
                                        err)
×
1455
                                continue
×
1456
                        }
1457

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

4✔
1467
                        // TODO(roasbeef): remove all together
4✔
1468
                        go func() {
8✔
1469
                                chanPoint := l.channel.ChannelPoint()
4✔
1470
                                l.cfg.Peer.WipeChannel(&chanPoint)
4✔
1471
                        }()
4✔
1472

1473
                        return
4✔
1474

1475
                case <-l.cfg.BatchTicker.Ticks():
4✔
1476
                        // Attempt to extend the remote commitment chain
4✔
1477
                        // including all the currently pending entries. If the
4✔
1478
                        // send was unsuccessful, then abandon the update,
4✔
1479
                        // waiting for the revocation window to open up.
4✔
1480
                        if !l.updateCommitTxOrFail(ctx) {
4✔
1481
                                return
×
1482
                        }
×
1483

1484
                case <-l.cfg.PendingCommitTicker.Ticks():
×
1485
                        l.failf(
×
1486
                                LinkFailureError{
×
1487
                                        code:          ErrRemoteUnresponsive,
×
1488
                                        FailureAction: LinkFailureDisconnect,
×
1489
                                },
×
1490
                                "unable to complete dance",
×
1491
                        )
×
1492
                        return
×
1493

1494
                // A message from the switch was just received. This indicates
1495
                // that the link is an intermediate hop in a multi-hop HTLC
1496
                // circuit.
1497
                case pkt := <-l.downstream:
4✔
1498
                        l.handleDownstreamPkt(ctx, pkt)
4✔
1499

1500
                // A message from the connected peer was just received. This
1501
                // indicates that we have a new incoming HTLC, either directly
1502
                // for us, or part of a multi-hop HTLC circuit.
1503
                case msg := <-l.upstream:
4✔
1504
                        l.handleUpstreamMsg(ctx, msg)
4✔
1505

1506
                // A htlc resolution is received. This means that we now have a
1507
                // resolution for a previously accepted htlc.
1508
                case hodlItem := <-l.hodlQueue.ChanOut():
4✔
1509
                        htlcResolution := hodlItem.(invoices.HtlcResolution)
4✔
1510
                        err := l.processHodlQueue(ctx, htlcResolution)
4✔
1511
                        switch err {
4✔
1512
                        // No error, success.
1513
                        case nil:
4✔
1514

1515
                        // If the duplicate keystone error was encountered,
1516
                        // fail back gracefully.
1517
                        case ErrDuplicateKeystone:
×
1518
                                l.failf(LinkFailureError{
×
1519
                                        code: ErrCircuitError,
×
1520
                                }, "process hodl queue: "+
×
1521
                                        "temporary circuit error: %v",
×
1522
                                        err,
×
1523
                                )
×
1524

1525
                        // Send an Error message to the peer.
1526
                        default:
×
1527
                                l.failf(LinkFailureError{
×
1528
                                        code: ErrInternalError,
×
1529
                                }, "process hodl queue: unable to update "+
×
1530
                                        "commitment: %v", err,
×
1531
                                )
×
1532
                        }
1533

1534
                case qReq := <-l.quiescenceReqs:
4✔
1535
                        l.quiescer.InitStfu(qReq)
4✔
1536

4✔
1537
                        if l.noDanglingUpdates(lntypes.Local) {
8✔
1538
                                err := l.quiescer.SendOwedStfu()
4✔
1539
                                if err != nil {
4✔
1540
                                        l.stfuFailf(
×
1541
                                                "SendOwedStfu: %s", err.Error(),
×
1542
                                        )
×
1543
                                        res := fn.Err[lntypes.ChannelParty](err)
×
1544
                                        qReq.Resolve(res)
×
1545
                                }
×
1546
                        }
1547

1548
                case <-l.cg.Done():
4✔
1549
                        return
4✔
1550
                }
1551
        }
1552
}
1553

1554
// processHodlQueue processes a received htlc resolution and continues reading
1555
// from the hodl queue until no more resolutions remain. When this function
1556
// returns without an error, the commit tx should be updated.
1557
func (l *channelLink) processHodlQueue(ctx context.Context,
1558
        firstResolution invoices.HtlcResolution) error {
4✔
1559

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

1573
                if err := l.processHtlcResolution(htlcResolution, hodlHtlc); err != nil {
4✔
1574
                        return err
×
1575
                }
×
1576

1577
                // Clean up hodl map.
1578
                delete(l.hodlMap, circuitKey)
4✔
1579

4✔
1580
                select {
4✔
1581
                case item := <-l.hodlQueue.ChanOut():
4✔
1582
                        htlcResolution = item.(invoices.HtlcResolution)
4✔
1583
                default:
4✔
1584
                        break loop
4✔
1585
                }
1586
        }
1587

1588
        // Update the commitment tx.
1589
        if err := l.updateCommitTx(ctx); err != nil {
4✔
1590
                return err
×
1591
        }
×
1592

1593
        return nil
4✔
1594
}
1595

1596
// processHtlcResolution applies a received htlc resolution to the provided
1597
// htlc. When this function returns without an error, the commit tx should be
1598
// updated.
1599
func (l *channelLink) processHtlcResolution(resolution invoices.HtlcResolution,
1600
        htlc hodlHtlc) error {
4✔
1601

4✔
1602
        circuitKey := resolution.CircuitKey()
4✔
1603

4✔
1604
        // Determine required action for the resolution based on the type of
4✔
1605
        // resolution we have received.
4✔
1606
        switch res := resolution.(type) {
4✔
1607
        // Settle htlcs that returned a settle resolution using the preimage
1608
        // in the resolution.
1609
        case *invoices.HtlcSettleResolution:
4✔
1610
                l.log.Debugf("received settle resolution for %v "+
4✔
1611
                        "with outcome: %v", circuitKey, res.Outcome)
4✔
1612

4✔
1613
                return l.settleHTLC(
4✔
1614
                        res.Preimage, htlc.add.ID, htlc.sourceRef,
4✔
1615
                )
4✔
1616

1617
        // For htlc failures, we get the relevant failure message based
1618
        // on the failure resolution and then fail the htlc.
1619
        case *invoices.HtlcFailResolution:
4✔
1620
                l.log.Debugf("received cancel resolution for "+
4✔
1621
                        "%v with outcome: %v", circuitKey, res.Outcome)
4✔
1622

4✔
1623
                // Get the lnwire failure message based on the resolution
4✔
1624
                // result.
4✔
1625
                failure := getResolutionFailure(res, htlc.add.Amount)
4✔
1626

4✔
1627
                l.sendHTLCError(
4✔
1628
                        htlc.add, htlc.sourceRef, failure, htlc.obfuscator,
4✔
1629
                        true,
4✔
1630
                )
4✔
1631
                return nil
4✔
1632

1633
        // Fail if we do not get a settle of fail resolution, since we
1634
        // are only expecting to handle settles and fails.
1635
        default:
×
1636
                return fmt.Errorf("unknown htlc resolution type: %T",
×
1637
                        resolution)
×
1638
        }
1639
}
1640

1641
// getResolutionFailure returns the wire message that a htlc resolution should
1642
// be failed with.
1643
func getResolutionFailure(resolution *invoices.HtlcFailResolution,
1644
        amount lnwire.MilliSatoshi) *LinkError {
4✔
1645

4✔
1646
        // If the resolution has been resolved as part of a MPP timeout,
4✔
1647
        // we need to fail the htlc with lnwire.FailMppTimeout.
4✔
1648
        if resolution.Outcome == invoices.ResultMppTimeout {
4✔
1649
                return NewDetailedLinkError(
×
1650
                        &lnwire.FailMPPTimeout{}, resolution.Outcome,
×
1651
                )
×
1652
        }
×
1653

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

4✔
1662
        return NewDetailedLinkError(incorrectDetails, resolution.Outcome)
4✔
1663
}
1664

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

1674
// handleDownstreamUpdateAdd processes an UpdateAddHTLC packet sent from the
1675
// downstream HTLC Switch.
1676
func (l *channelLink) handleDownstreamUpdateAdd(ctx context.Context,
1677
        pkt *htlcPacket) error {
4✔
1678

4✔
1679
        htlc, ok := pkt.htlc.(*lnwire.UpdateAddHTLC)
4✔
1680
        if !ok {
4✔
1681
                return errors.New("not an UpdateAddHTLC packet")
×
1682
        }
×
1683

1684
        // If we are flushing the link in the outgoing direction or we have
1685
        // already sent Stfu, then we can't add new htlcs to the link and we
1686
        // need to bounce it.
1687
        if l.IsFlushing(Outgoing) || !l.quiescer.CanSendUpdates() {
4✔
1688
                l.mailBox.FailAdd(pkt)
×
1689

×
1690
                return NewDetailedLinkError(
×
1691
                        &lnwire.FailTemporaryChannelFailure{},
×
1692
                        OutgoingFailureLinkNotEligible,
×
1693
                )
×
1694
        }
×
1695

1696
        // If hodl.AddOutgoing mode is active, we exit early to simulate
1697
        // arbitrary delays between the switch adding an ADD to the
1698
        // mailbox, and the HTLC being added to the commitment state.
1699
        if l.cfg.HodlMask.Active(hodl.AddOutgoing) {
4✔
1700
                l.log.Warnf(hodl.AddOutgoing.Warning())
×
1701
                l.mailBox.AckPacket(pkt.inKey())
×
1702
                return nil
×
1703
        }
×
1704

1705
        // Check if we can add the HTLC here without exceededing the max fee
1706
        // exposure threshold.
1707
        if l.isOverexposedWithHtlc(htlc, false) {
4✔
1708
                l.log.Debugf("Unable to handle downstream HTLC - max fee " +
×
1709
                        "exposure exceeded")
×
1710

×
1711
                l.mailBox.FailAdd(pkt)
×
1712

×
1713
                return NewDetailedLinkError(
×
1714
                        lnwire.NewTemporaryChannelFailure(nil),
×
1715
                        OutgoingFailureDownstreamHtlcAdd,
×
1716
                )
×
1717
        }
×
1718

1719
        // A new payment has been initiated via the downstream channel,
1720
        // so we add the new HTLC to our local log, then update the
1721
        // commitment chains.
1722
        htlc.ChanID = l.ChanID()
4✔
1723
        openCircuitRef := pkt.inKey()
4✔
1724

4✔
1725
        // We enforce the fee buffer for the commitment transaction because
4✔
1726
        // we are in control of adding this htlc. Nothing has locked-in yet so
4✔
1727
        // we can securely enforce the fee buffer which is only relevant if we
4✔
1728
        // are the initiator of the channel.
4✔
1729
        index, err := l.channel.AddHTLC(htlc, &openCircuitRef)
4✔
1730
        if err != nil {
8✔
1731
                // The HTLC was unable to be added to the state machine,
4✔
1732
                // as a result, we'll signal the switch to cancel the
4✔
1733
                // pending payment.
4✔
1734
                l.log.Warnf("Unable to handle downstream add HTLC: %v",
4✔
1735
                        err)
4✔
1736

4✔
1737
                // Remove this packet from the link's mailbox, this
4✔
1738
                // prevents it from being reprocessed if the link
4✔
1739
                // restarts and resets it mailbox. If this response
4✔
1740
                // doesn't make it back to the originating link, it will
4✔
1741
                // be rejected upon attempting to reforward the Add to
4✔
1742
                // the switch, since the circuit was never fully opened,
4✔
1743
                // and the forwarding package shows it as
4✔
1744
                // unacknowledged.
4✔
1745
                l.mailBox.FailAdd(pkt)
4✔
1746

4✔
1747
                return NewDetailedLinkError(
4✔
1748
                        lnwire.NewTemporaryChannelFailure(nil),
4✔
1749
                        OutgoingFailureDownstreamHtlcAdd,
4✔
1750
                )
4✔
1751
        }
4✔
1752

1753
        l.log.Tracef("received downstream htlc: payment_hash=%x, "+
4✔
1754
                "local_log_index=%v, pend_updates=%v",
4✔
1755
                htlc.PaymentHash[:], index,
4✔
1756
                l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote))
4✔
1757

4✔
1758
        pkt.outgoingChanID = l.ShortChanID()
4✔
1759
        pkt.outgoingHTLCID = index
4✔
1760
        htlc.ID = index
4✔
1761

4✔
1762
        l.log.Debugf("queueing keystone of ADD open circuit: %s->%s",
4✔
1763
                pkt.inKey(), pkt.outKey())
4✔
1764

4✔
1765
        l.openedCircuits = append(l.openedCircuits, pkt.inKey())
4✔
1766
        l.keystoneBatch = append(l.keystoneBatch, pkt.keystone())
4✔
1767

4✔
1768
        _ = l.cfg.Peer.SendMessage(false, htlc)
4✔
1769

4✔
1770
        // Send a forward event notification to htlcNotifier.
4✔
1771
        l.cfg.HtlcNotifier.NotifyForwardingEvent(
4✔
1772
                newHtlcKey(pkt),
4✔
1773
                HtlcInfo{
4✔
1774
                        IncomingTimeLock: pkt.incomingTimeout,
4✔
1775
                        IncomingAmt:      pkt.incomingAmount,
4✔
1776
                        OutgoingTimeLock: htlc.Expiry,
4✔
1777
                        OutgoingAmt:      htlc.Amount,
4✔
1778
                },
4✔
1779
                getEventType(pkt),
4✔
1780
        )
4✔
1781

4✔
1782
        l.tryBatchUpdateCommitTx(ctx)
4✔
1783

4✔
1784
        return nil
4✔
1785
}
1786

1787
// handleDownstreamPkt processes an HTLC packet sent from the downstream HTLC
1788
// Switch. Possible messages sent by the switch include requests to forward new
1789
// HTLCs, timeout previously cleared HTLCs, and finally to settle currently
1790
// cleared HTLCs with the upstream peer.
1791
//
1792
// TODO(roasbeef): add sync ntfn to ensure switch always has consistent view?
1793
func (l *channelLink) handleDownstreamPkt(ctx context.Context, pkt *htlcPacket) {
4✔
1794
        if pkt.htlc.MsgType().IsChannelUpdate() &&
4✔
1795
                !l.quiescer.CanSendUpdates() {
4✔
1796

×
1797
                l.log.Warnf("unable to process channel update. "+
×
1798
                        "ChannelID=%v is quiescent.", l.ChanID)
×
1799

×
1800
                return
×
1801
        }
×
1802

1803
        switch htlc := pkt.htlc.(type) {
4✔
1804
        case *lnwire.UpdateAddHTLC:
4✔
1805
                // Handle add message. The returned error can be ignored,
4✔
1806
                // because it is also sent through the mailbox.
4✔
1807
                _ = l.handleDownstreamUpdateAdd(ctx, pkt)
4✔
1808

1809
        case *lnwire.UpdateFulfillHTLC:
4✔
1810
                // If hodl.SettleOutgoing mode is active, we exit early to
4✔
1811
                // simulate arbitrary delays between the switch adding the
4✔
1812
                // SETTLE to the mailbox, and the HTLC being added to the
4✔
1813
                // commitment state.
4✔
1814
                if l.cfg.HodlMask.Active(hodl.SettleOutgoing) {
4✔
1815
                        l.log.Warnf(hodl.SettleOutgoing.Warning())
×
1816
                        l.mailBox.AckPacket(pkt.inKey())
×
1817
                        return
×
1818
                }
×
1819

1820
                // An HTLC we forward to the switch has just settled somewhere
1821
                // upstream. Therefore we settle the HTLC within the our local
1822
                // state machine.
1823
                inKey := pkt.inKey()
4✔
1824
                err := l.channel.SettleHTLC(
4✔
1825
                        htlc.PaymentPreimage,
4✔
1826
                        pkt.incomingHTLCID,
4✔
1827
                        pkt.sourceRef,
4✔
1828
                        pkt.destRef,
4✔
1829
                        &inKey,
4✔
1830
                )
4✔
1831
                if err != nil {
4✔
1832
                        l.log.Errorf("unable to settle incoming HTLC for "+
×
1833
                                "circuit-key=%v: %v", inKey, err)
×
1834

×
1835
                        // If the HTLC index for Settle response was not known
×
1836
                        // to our commitment state, it has already been
×
1837
                        // cleaned up by a prior response. We'll thus try to
×
1838
                        // clean up any lingering state to ensure we don't
×
1839
                        // continue reforwarding.
×
1840
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
×
1841
                                l.cleanupSpuriousResponse(pkt)
×
1842
                        }
×
1843

1844
                        // Remove the packet from the link's mailbox to ensure
1845
                        // it doesn't get replayed after a reconnection.
1846
                        l.mailBox.AckPacket(inKey)
×
1847

×
1848
                        return
×
1849
                }
1850

1851
                l.log.Debugf("queueing removal of SETTLE closed circuit: "+
4✔
1852
                        "%s->%s", pkt.inKey(), pkt.outKey())
4✔
1853

4✔
1854
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
4✔
1855

4✔
1856
                // With the HTLC settled, we'll need to populate the wire
4✔
1857
                // message to target the specific channel and HTLC to be
4✔
1858
                // canceled.
4✔
1859
                htlc.ChanID = l.ChanID()
4✔
1860
                htlc.ID = pkt.incomingHTLCID
4✔
1861

4✔
1862
                // Then we send the HTLC settle message to the connected peer
4✔
1863
                // so we can continue the propagation of the settle message.
4✔
1864
                l.cfg.Peer.SendMessage(false, htlc)
4✔
1865

4✔
1866
                // Send a settle event notification to htlcNotifier.
4✔
1867
                l.cfg.HtlcNotifier.NotifySettleEvent(
4✔
1868
                        newHtlcKey(pkt),
4✔
1869
                        htlc.PaymentPreimage,
4✔
1870
                        getEventType(pkt),
4✔
1871
                )
4✔
1872

4✔
1873
                // Immediately update the commitment tx to minimize latency.
4✔
1874
                l.updateCommitTxOrFail(ctx)
4✔
1875

1876
        case *lnwire.UpdateFailHTLC:
4✔
1877
                // If hodl.FailOutgoing mode is active, we exit early to
4✔
1878
                // simulate arbitrary delays between the switch adding a FAIL to
4✔
1879
                // the mailbox, and the HTLC being added to the commitment
4✔
1880
                // state.
4✔
1881
                if l.cfg.HodlMask.Active(hodl.FailOutgoing) {
4✔
1882
                        l.log.Warnf(hodl.FailOutgoing.Warning())
×
1883
                        l.mailBox.AckPacket(pkt.inKey())
×
1884
                        return
×
1885
                }
×
1886

1887
                // An HTLC cancellation has been triggered somewhere upstream,
1888
                // we'll remove then HTLC from our local state machine.
1889
                inKey := pkt.inKey()
4✔
1890
                err := l.channel.FailHTLC(
4✔
1891
                        pkt.incomingHTLCID,
4✔
1892
                        htlc.Reason,
4✔
1893
                        pkt.sourceRef,
4✔
1894
                        pkt.destRef,
4✔
1895
                        &inKey,
4✔
1896
                )
4✔
1897
                if err != nil {
8✔
1898
                        l.log.Errorf("unable to cancel incoming HTLC for "+
4✔
1899
                                "circuit-key=%v: %v", inKey, err)
4✔
1900

4✔
1901
                        // If the HTLC index for Fail response was not known to
4✔
1902
                        // our commitment state, it has already been cleaned up
4✔
1903
                        // by a prior response. We'll thus try to clean up any
4✔
1904
                        // lingering state to ensure we don't continue
4✔
1905
                        // reforwarding.
4✔
1906
                        if _, ok := err.(lnwallet.ErrUnknownHtlcIndex); ok {
4✔
1907
                                l.cleanupSpuriousResponse(pkt)
×
1908
                        }
×
1909

1910
                        // Remove the packet from the link's mailbox to ensure
1911
                        // it doesn't get replayed after a reconnection.
1912
                        l.mailBox.AckPacket(inKey)
4✔
1913

4✔
1914
                        return
4✔
1915
                }
1916

1917
                l.log.Debugf("queueing removal of FAIL closed circuit: %s->%s",
4✔
1918
                        pkt.inKey(), pkt.outKey())
4✔
1919

4✔
1920
                l.closedCircuits = append(l.closedCircuits, pkt.inKey())
4✔
1921

4✔
1922
                // With the HTLC removed, we'll need to populate the wire
4✔
1923
                // message to target the specific channel and HTLC to be
4✔
1924
                // canceled. The "Reason" field will have already been set
4✔
1925
                // within the switch.
4✔
1926
                htlc.ChanID = l.ChanID()
4✔
1927
                htlc.ID = pkt.incomingHTLCID
4✔
1928

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

×
1942
                        return
×
1943
                }
×
1944

1945
                // If the packet does not have a link failure set, it failed
1946
                // further down the route so we notify a forwarding failure.
1947
                // Otherwise, we notify a link failure because it failed at our
1948
                // node.
1949
                if pkt.linkFailure != nil {
8✔
1950
                        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
4✔
1951
                                newHtlcKey(pkt),
4✔
1952
                                newHtlcInfo(pkt),
4✔
1953
                                getEventType(pkt),
4✔
1954
                                pkt.linkFailure,
4✔
1955
                                false,
4✔
1956
                        )
4✔
1957
                } else {
8✔
1958
                        l.cfg.HtlcNotifier.NotifyForwardingFailEvent(
4✔
1959
                                newHtlcKey(pkt), getEventType(pkt),
4✔
1960
                        )
4✔
1961
                }
4✔
1962

1963
                // Immediately update the commitment tx to minimize latency.
1964
                l.updateCommitTxOrFail(ctx)
4✔
1965
        }
1966
}
1967

1968
// tryBatchUpdateCommitTx updates the commitment transaction if the batch is
1969
// full.
1970
func (l *channelLink) tryBatchUpdateCommitTx(ctx context.Context) {
4✔
1971
        pending := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
4✔
1972
        if pending < uint64(l.cfg.BatchSize) {
8✔
1973
                return
4✔
1974
        }
4✔
1975

1976
        l.updateCommitTxOrFail(ctx)
4✔
1977
}
1978

1979
// cleanupSpuriousResponse attempts to ack any AddRef or SettleFailRef
1980
// associated with this packet. If successful in doing so, it will also purge
1981
// the open circuit from the circuit map and remove the packet from the link's
1982
// mailbox.
1983
func (l *channelLink) cleanupSpuriousResponse(pkt *htlcPacket) {
×
1984
        inKey := pkt.inKey()
×
1985

×
1986
        l.log.Debugf("cleaning up spurious response for incoming "+
×
1987
                "circuit-key=%v", inKey)
×
1988

×
1989
        // If the htlc packet doesn't have a source reference, it is unsafe to
×
1990
        // proceed, as skipping this ack may cause the htlc to be reforwarded.
×
1991
        if pkt.sourceRef == nil {
×
1992
                l.log.Errorf("unable to cleanup response for incoming "+
×
1993
                        "circuit-key=%v, does not contain source reference",
×
1994
                        inKey)
×
1995
                return
×
1996
        }
×
1997

1998
        // If the source reference is present,  we will try to prevent this link
1999
        // from resending the packet to the switch. To do so, we ack the AddRef
2000
        // of the incoming HTLC belonging to this link.
2001
        err := l.channel.AckAddHtlcs(*pkt.sourceRef)
×
2002
        if err != nil {
×
2003
                l.log.Errorf("unable to ack AddRef for incoming "+
×
2004
                        "circuit-key=%v: %v", inKey, err)
×
2005

×
2006
                // If this operation failed, it is unsafe to attempt removal of
×
2007
                // the destination reference or circuit, so we exit early. The
×
2008
                // cleanup may proceed with a different packet in the future
×
2009
                // that succeeds on this step.
×
2010
                return
×
2011
        }
×
2012

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

2032
        l.log.Debugf("deleting circuit for incoming circuit-key=%x", inKey)
×
2033

×
2034
        // With all known references acked, we can now safely delete the circuit
×
2035
        // from the switch's circuit map, as the state is no longer needed.
×
2036
        err = l.cfg.Circuits.DeleteCircuits(inKey)
×
2037
        if err != nil {
×
2038
                l.log.Errorf("unable to delete circuit for "+
×
2039
                        "circuit-key=%v: %v", inKey, err)
×
2040
        }
×
2041
}
2042

2043
// handleUpstreamMsg processes wire messages related to commitment state
2044
// updates from the upstream peer. The upstream peer is the peer whom we have a
2045
// direct channel with, updating our respective commitment chains.
2046
func (l *channelLink) handleUpstreamMsg(ctx context.Context, msg lnwire.Message) {
4✔
2047
        // First check if the message is an update and we are capable of
4✔
2048
        // receiving updates right now.
4✔
2049
        if msg.MsgType().IsChannelUpdate() && !l.quiescer.CanRecvUpdates() {
4✔
2050
                l.stfuFailf("update received after stfu: %T", msg)
×
2051
                return
×
2052
        }
×
2053

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

×
2086
                        return
×
2087
                }
×
2088

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

×
2099
                        return
×
2100
                }
×
2101

2102
                // We have to check the limit here rather than later in the
2103
                // switch because the counterparty can keep sending HTLC's
2104
                // without sending a revoke. This would mean that the switch
2105
                // check would only occur later.
2106
                if l.isOverexposedWithHtlc(msg, true) {
4✔
2107
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2108
                                "peer sent us an HTLC that exceeded our max "+
×
2109
                                        "fee exposure")
×
2110

×
2111
                        return
×
2112
                }
×
2113

2114
                // We just received an add request from an upstream peer, so we
2115
                // add it to our state machine, then add the HTLC to our
2116
                // "settle" list in the event that we know the preimage.
2117
                index, err := l.channel.ReceiveHTLC(msg)
4✔
2118
                if err != nil {
4✔
2119
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2120
                                "unable to handle upstream add HTLC: %v", err)
×
2121
                        return
×
2122
                }
×
2123

2124
                l.log.Tracef("receive upstream htlc with payment hash(%x), "+
4✔
2125
                        "assigning index: %v", msg.PaymentHash[:], index)
4✔
2126

2127
        case *lnwire.UpdateFulfillHTLC:
4✔
2128
                pre := msg.PaymentPreimage
4✔
2129
                idx := msg.ID
4✔
2130

4✔
2131
                // Before we pipeline the settle, we'll check the set of active
4✔
2132
                // htlc's to see if the related UpdateAddHTLC has been fully
4✔
2133
                // locked-in.
4✔
2134
                var lockedin bool
4✔
2135
                htlcs := l.channel.ActiveHtlcs()
4✔
2136
                for _, add := range htlcs {
8✔
2137
                        // The HTLC will be outgoing and match idx.
4✔
2138
                        if !add.Incoming && add.HtlcIndex == idx {
8✔
2139
                                lockedin = true
4✔
2140
                                break
4✔
2141
                        }
2142
                }
2143

2144
                if !lockedin {
4✔
2145
                        l.failf(
×
2146
                                LinkFailureError{code: ErrInvalidUpdate},
×
2147
                                "unable to handle upstream settle",
×
2148
                        )
×
2149
                        return
×
2150
                }
×
2151

2152
                if err := l.channel.ReceiveHTLCSettle(pre, idx); err != nil {
8✔
2153
                        l.failf(
4✔
2154
                                LinkFailureError{
4✔
2155
                                        code:          ErrInvalidUpdate,
4✔
2156
                                        FailureAction: LinkFailureForceClose,
4✔
2157
                                },
4✔
2158
                                "unable to handle upstream settle HTLC: %v", err,
4✔
2159
                        )
4✔
2160
                        return
4✔
2161
                }
4✔
2162

2163
                settlePacket := &htlcPacket{
4✔
2164
                        outgoingChanID: l.ShortChanID(),
4✔
2165
                        outgoingHTLCID: idx,
4✔
2166
                        htlc: &lnwire.UpdateFulfillHTLC{
4✔
2167
                                PaymentPreimage: pre,
4✔
2168
                        },
4✔
2169
                }
4✔
2170

4✔
2171
                // Add the newly discovered preimage to our growing list of
4✔
2172
                // uncommitted preimage. These will be written to the witness
4✔
2173
                // cache just before accepting the next commitment signature
4✔
2174
                // from the remote peer.
4✔
2175
                l.uncommittedPreimages = append(l.uncommittedPreimages, pre)
4✔
2176

4✔
2177
                // Pipeline this settle, send it to the switch.
4✔
2178
                go l.forwardBatch(false, settlePacket)
4✔
2179

2180
        case *lnwire.UpdateFailMalformedHTLC:
4✔
2181
                // Convert the failure type encoded within the HTLC fail
4✔
2182
                // message to the proper generic lnwire error code.
4✔
2183
                var failure lnwire.FailureMessage
4✔
2184
                switch msg.FailureCode {
4✔
2185
                case lnwire.CodeInvalidOnionVersion:
4✔
2186
                        failure = &lnwire.FailInvalidOnionVersion{
4✔
2187
                                OnionSHA256: msg.ShaOnionBlob,
4✔
2188
                        }
4✔
2189
                case lnwire.CodeInvalidOnionHmac:
×
2190
                        failure = &lnwire.FailInvalidOnionHmac{
×
2191
                                OnionSHA256: msg.ShaOnionBlob,
×
2192
                        }
×
2193

2194
                case lnwire.CodeInvalidOnionKey:
×
2195
                        failure = &lnwire.FailInvalidOnionKey{
×
2196
                                OnionSHA256: msg.ShaOnionBlob,
×
2197
                        }
×
2198

2199
                // Handle malformed errors that are part of a blinded route.
2200
                // This case is slightly different, because we expect every
2201
                // relaying node in the blinded portion of the route to send
2202
                // malformed errors. If we're also a relaying node, we're
2203
                // likely going to switch this error out anyway for our own
2204
                // malformed error, but we handle the case here for
2205
                // completeness.
2206
                case lnwire.CodeInvalidBlinding:
4✔
2207
                        failure = &lnwire.FailInvalidBlinding{
4✔
2208
                                OnionSHA256: msg.ShaOnionBlob,
4✔
2209
                        }
4✔
2210

2211
                default:
×
2212
                        l.log.Warnf("unexpected failure code received in "+
×
2213
                                "UpdateFailMailformedHTLC: %v", msg.FailureCode)
×
2214

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

2229
                // With the error parsed, we'll convert the into it's opaque
2230
                // form.
2231
                var b bytes.Buffer
4✔
2232
                if err := lnwire.EncodeFailure(&b, failure, 0); err != nil {
4✔
2233
                        l.log.Errorf("unable to encode malformed error: %v", err)
×
2234
                        return
×
2235
                }
×
2236

2237
                // If remote side have been unable to parse the onion blob we
2238
                // have sent to it, than we should transform the malformed HTLC
2239
                // message to the usual HTLC fail message.
2240
                err := l.channel.ReceiveFailHTLC(msg.ID, b.Bytes())
4✔
2241
                if err != nil {
4✔
2242
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2243
                                "unable to handle upstream fail HTLC: %v", err)
×
2244
                        return
×
2245
                }
×
2246

2247
        case *lnwire.UpdateFailHTLC:
4✔
2248
                // Verify that the failure reason is at least 256 bytes plus
4✔
2249
                // overhead.
4✔
2250
                const minimumFailReasonLength = lnwire.FailureMessageLength +
4✔
2251
                        2 + 2 + 32
4✔
2252

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

×
2272
                                return
×
2273
                        }
×
2274
                }
2275

2276
                // Add fail to the update log.
2277
                idx := msg.ID
4✔
2278
                err := l.channel.ReceiveFailHTLC(idx, msg.Reason[:])
4✔
2279
                if err != nil {
4✔
2280
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2281
                                "unable to handle upstream fail HTLC: %v", err)
×
2282
                        return
×
2283
                }
×
2284

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

2307
                // Instead of truncating the slice to conserve memory
2308
                // allocations, we simply set the uncommitted preimage slice to
2309
                // nil so that a new one will be initialized if any more
2310
                // witnesses are discovered. We do this because the maximum size
2311
                // that the slice can occupy is 15KB, and we want to ensure we
2312
                // release that memory back to the runtime.
2313
                l.uncommittedPreimages = nil
4✔
2314

4✔
2315
                // We just received a new updates to our local commitment
4✔
2316
                // chain, validate this new commitment, closing the link if
4✔
2317
                // invalid.
4✔
2318
                auxSigBlob, err := msg.CustomRecords.Serialize()
4✔
2319
                if err != nil {
4✔
2320
                        l.failf(
×
2321
                                LinkFailureError{code: ErrInvalidCommitment},
×
2322
                                "unable to serialize custom records: %v", err,
×
2323
                        )
×
2324

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

2358
                // As we've just accepted a new state, we'll now
2359
                // immediately send the remote peer a revocation for our prior
2360
                // state.
2361
                nextRevocation, currentHtlcs, finalHTLCs, err :=
4✔
2362
                        l.channel.RevokeCurrentCommitment()
4✔
2363
                if err != nil {
4✔
2364
                        l.log.Errorf("unable to revoke commitment: %v", err)
×
2365

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

2387
                // As soon as we are ready to send our next revocation, we can
2388
                // invoke the incoming commit hooks.
2389
                l.RWMutex.Lock()
4✔
2390
                l.incomingCommitHooks.invoke()
4✔
2391
                l.RWMutex.Unlock()
4✔
2392

4✔
2393
                l.cfg.Peer.SendMessage(false, nextRevocation)
4✔
2394

4✔
2395
                // Notify the incoming htlcs of which the resolutions were
4✔
2396
                // locked in.
4✔
2397
                for id, settled := range finalHTLCs {
8✔
2398
                        l.cfg.HtlcNotifier.NotifyFinalHtlcEvent(
4✔
2399
                                models.CircuitKey{
4✔
2400
                                        ChanID: l.ShortChanID(),
4✔
2401
                                        HtlcID: id,
4✔
2402
                                },
4✔
2403
                                channeldb.FinalHtlcInfo{
4✔
2404
                                        Settled:  settled,
4✔
2405
                                        Offchain: true,
4✔
2406
                                },
4✔
2407
                        )
4✔
2408
                }
4✔
2409

2410
                // Since we just revoked our commitment, we may have a new set
2411
                // of HTLC's on our commitment, so we'll send them using our
2412
                // function closure NotifyContractUpdate.
2413
                newUpdate := &contractcourt.ContractUpdate{
4✔
2414
                        HtlcKey: contractcourt.LocalHtlcSet,
4✔
2415
                        Htlcs:   currentHtlcs,
4✔
2416
                }
4✔
2417
                err = l.cfg.NotifyContractUpdate(newUpdate)
4✔
2418
                if err != nil {
4✔
2419
                        l.log.Errorf("unable to notify contract update: %v",
×
2420
                                err)
×
2421
                        return
×
2422
                }
×
2423

2424
                select {
4✔
NEW
2425
                case <-l.cg.Done():
×
2426
                        return
×
2427
                default:
4✔
2428
                }
2429

2430
                // If the remote party initiated the state transition,
2431
                // we'll reply with a signature to provide them with their
2432
                // version of the latest commitment. Otherwise, both commitment
2433
                // chains are fully synced from our PoV, then we don't need to
2434
                // reply with a signature as both sides already have a
2435
                // commitment with the latest accepted.
2436
                if l.channel.OweCommitment() {
8✔
2437
                        if !l.updateCommitTxOrFail(ctx) {
4✔
2438
                                return
×
2439
                        }
×
2440
                }
2441

2442
                // If we need to send out an Stfu, this would be the time to do
2443
                // so.
2444
                if l.noDanglingUpdates(lntypes.Local) {
8✔
2445
                        err = l.quiescer.SendOwedStfu()
4✔
2446
                        if err != nil {
4✔
2447
                                l.stfuFailf("sendOwedStfu: %v", err.Error())
×
2448
                        }
×
2449
                }
2450

2451
                // Now that we have finished processing the incoming CommitSig
2452
                // and sent out our RevokeAndAck, we invoke the flushHooks if
2453
                // the channel state is clean.
2454
                l.RWMutex.Lock()
4✔
2455
                if l.channel.IsChannelClean() {
8✔
2456
                        l.flushHooks.invoke()
4✔
2457
                }
4✔
2458
                l.RWMutex.Unlock()
4✔
2459

2460
        case *lnwire.RevokeAndAck:
4✔
2461
                // We've received a revocation from the remote chain, if valid,
4✔
2462
                // this moves the remote chain forward, and expands our
4✔
2463
                // revocation window.
4✔
2464

4✔
2465
                // We now process the message and advance our remote commit
4✔
2466
                // chain.
4✔
2467
                fwdPkg, remoteHTLCs, err := l.channel.ReceiveRevocation(msg)
4✔
2468
                if err != nil {
4✔
2469
                        // TODO(halseth): force close?
×
2470
                        l.failf(
×
2471
                                LinkFailureError{
×
2472
                                        code:          ErrInvalidRevocation,
×
2473
                                        FailureAction: LinkFailureDisconnect,
×
2474
                                },
×
2475
                                "unable to accept revocation: %v", err,
×
2476
                        )
×
2477
                        return
×
2478
                }
×
2479

2480
                // The remote party now has a new primary commitment, so we'll
2481
                // update the contract court to be aware of this new set (the
2482
                // prior old remote pending).
2483
                newUpdate := &contractcourt.ContractUpdate{
4✔
2484
                        HtlcKey: contractcourt.RemoteHtlcSet,
4✔
2485
                        Htlcs:   remoteHTLCs,
4✔
2486
                }
4✔
2487
                err = l.cfg.NotifyContractUpdate(newUpdate)
4✔
2488
                if err != nil {
4✔
2489
                        l.log.Errorf("unable to notify contract update: %v",
×
2490
                                err)
×
2491
                        return
×
2492
                }
×
2493

2494
                select {
4✔
NEW
2495
                case <-l.cg.Done():
×
2496
                        return
×
2497
                default:
4✔
2498
                }
2499

2500
                // If we have a tower client for this channel type, we'll
2501
                // create a backup for the current state.
2502
                if l.cfg.TowerClient != nil {
8✔
2503
                        state := l.channel.State()
4✔
2504
                        chanID := l.ChanID()
4✔
2505

4✔
2506
                        err = l.cfg.TowerClient.BackupState(
4✔
2507
                                &chanID, state.RemoteCommitment.CommitHeight-1,
4✔
2508
                        )
4✔
2509
                        if err != nil {
4✔
2510
                                l.failf(LinkFailureError{
×
2511
                                        code: ErrInternalError,
×
2512
                                }, "unable to queue breach backup: %v", err)
×
2513
                                return
×
2514
                        }
×
2515
                }
2516

2517
                // If we can send updates then we can process adds in case we
2518
                // are the exit hop and need to send back resolutions, or in
2519
                // case there are validity issues with the packets. Otherwise
2520
                // we defer the action until resume.
2521
                //
2522
                // We are free to process the settles and fails without this
2523
                // check since processing those can't result in further updates
2524
                // to this channel link.
2525
                if l.quiescer.CanSendUpdates() {
8✔
2526
                        l.processRemoteAdds(fwdPkg)
4✔
2527
                } else {
4✔
2528
                        l.quiescer.OnResume(func() {
×
2529
                                l.processRemoteAdds(fwdPkg)
×
2530
                        })
×
2531
                }
2532
                l.processRemoteSettleFails(fwdPkg)
4✔
2533

4✔
2534
                // If the link failed during processing the adds, we must
4✔
2535
                // return to ensure we won't attempted to update the state
4✔
2536
                // further.
4✔
2537
                if l.failed {
8✔
2538
                        return
4✔
2539
                }
4✔
2540

2541
                // The revocation window opened up. If there are pending local
2542
                // updates, try to update the commit tx. Pending updates could
2543
                // already have been present because of a previously failed
2544
                // update to the commit tx or freshly added in by
2545
                // processRemoteAdds. Also in case there are no local updates,
2546
                // but there are still remote updates that are not in the remote
2547
                // commit tx yet, send out an update.
2548
                if l.channel.OweCommitment() {
8✔
2549
                        if !l.updateCommitTxOrFail(ctx) {
4✔
2550
                                return
×
2551
                        }
×
2552
                }
2553

2554
                // Now that we have finished processing the RevokeAndAck, we
2555
                // can invoke the flushHooks if the channel state is clean.
2556
                l.RWMutex.Lock()
4✔
2557
                if l.channel.IsChannelClean() {
8✔
2558
                        l.flushHooks.invoke()
4✔
2559
                }
4✔
2560
                l.RWMutex.Unlock()
4✔
2561

2562
        case *lnwire.UpdateFee:
×
2563
                // Check and see if their proposed fee-rate would make us
×
2564
                // exceed the fee threshold.
×
2565
                fee := chainfee.SatPerKWeight(msg.FeePerKw)
×
2566

×
2567
                isDust, err := l.exceedsFeeExposureLimit(fee)
×
2568
                if err != nil {
×
2569
                        // This shouldn't typically happen. If it does, it
×
2570
                        // indicates something is wrong with our channel state.
×
2571
                        l.log.Errorf("Unable to determine if fee threshold " +
×
2572
                                "exceeded")
×
2573
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2574
                                "error calculating fee exposure: %v", err)
×
2575

×
2576
                        return
×
2577
                }
×
2578

2579
                if isDust {
×
2580
                        // The proposed fee-rate makes us exceed the fee
×
2581
                        // threshold.
×
2582
                        l.failf(LinkFailureError{code: ErrInternalError},
×
2583
                                "fee threshold exceeded: %v", err)
×
2584
                        return
×
2585
                }
×
2586

2587
                // We received fee update from peer. If we are the initiator we
2588
                // will fail the channel, if not we will apply the update.
2589
                if err := l.channel.ReceiveUpdateFee(fee); err != nil {
×
2590
                        l.failf(LinkFailureError{code: ErrInvalidUpdate},
×
2591
                                "error receiving fee update: %v", err)
×
2592
                        return
×
2593
                }
×
2594

2595
                // Update the mailbox's feerate as well.
2596
                l.mailBox.SetFeeRate(fee)
×
2597

2598
        case *lnwire.Stfu:
4✔
2599
                err := l.handleStfu(msg)
4✔
2600
                if err != nil {
4✔
2601
                        l.stfuFailf("handleStfu: %v", err.Error())
×
2602
                }
×
2603

2604
        // In the case where we receive a warning message from our peer, just
2605
        // log it and move on. We choose not to disconnect from our peer,
2606
        // although we "MAY" do so according to the specification.
2607
        case *lnwire.Warning:
×
2608
                l.log.Warnf("received warning message from peer: %v",
×
2609
                        msg.Warning())
×
2610

2611
        case *lnwire.Error:
4✔
2612
                // Error received from remote, MUST fail channel, but should
4✔
2613
                // only print the contents of the error message if all
4✔
2614
                // characters are printable ASCII.
4✔
2615
                l.failf(
4✔
2616
                        LinkFailureError{
4✔
2617
                                code: ErrRemoteError,
4✔
2618

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

2634
}
2635

2636
// handleStfu implements the top-level logic for handling the Stfu message from
2637
// our peer.
2638
func (l *channelLink) handleStfu(stfu *lnwire.Stfu) error {
4✔
2639
        if !l.noDanglingUpdates(lntypes.Remote) {
4✔
2640
                return ErrPendingRemoteUpdates
×
2641
        }
×
2642
        err := l.quiescer.RecvStfu(*stfu)
4✔
2643
        if err != nil {
4✔
2644
                return err
×
2645
        }
×
2646

2647
        // If we can immediately send an Stfu response back, we will.
2648
        if l.noDanglingUpdates(lntypes.Local) {
8✔
2649
                return l.quiescer.SendOwedStfu()
4✔
2650
        }
4✔
2651

2652
        return nil
×
2653
}
2654

2655
// stfuFailf fails the link in the case where the requirements of the quiescence
2656
// protocol are violated. In all cases we opt to drop the connection as only
2657
// link state (as opposed to channel state) is affected.
2658
func (l *channelLink) stfuFailf(format string, args ...interface{}) {
×
2659
        l.failf(LinkFailureError{
×
2660
                code:             ErrStfuViolation,
×
2661
                FailureAction:    LinkFailureDisconnect,
×
2662
                PermanentFailure: false,
×
2663
                Warning:          true,
×
2664
        }, format, args...)
×
2665
}
×
2666

2667
// noDanglingUpdates returns true when there are 0 updates that were originally
2668
// issued by whose on either the Local or Remote commitment transaction.
2669
func (l *channelLink) noDanglingUpdates(whose lntypes.ChannelParty) bool {
4✔
2670
        pendingOnLocal := l.channel.NumPendingUpdates(
4✔
2671
                whose, lntypes.Local,
4✔
2672
        )
4✔
2673
        pendingOnRemote := l.channel.NumPendingUpdates(
4✔
2674
                whose, lntypes.Remote,
4✔
2675
        )
4✔
2676

4✔
2677
        return pendingOnLocal == 0 && pendingOnRemote == 0
4✔
2678
}
4✔
2679

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

2699
                l.log.Debugf("removing Add packet %s from mailbox", inKey)
4✔
2700
                l.mailBox.AckPacket(inKey)
4✔
2701
        }
2702

2703
        // Now, we will delete all circuits closed by the previous commitment
2704
        // signature, which is the result of downstream Settle/Fail packets. We
2705
        // batch them here to ensure circuits are closed atomically and for
2706
        // performance.
2707
        err := l.cfg.Circuits.DeleteCircuits(l.closedCircuits...)
4✔
2708
        switch err {
4✔
2709
        case nil:
4✔
2710
                // Successful deletion.
2711

2712
        default:
×
2713
                l.log.Errorf("unable to delete %d circuits: %v",
×
2714
                        len(l.closedCircuits), err)
×
2715
                return err
×
2716
        }
2717

2718
        // With the circuits removed from memory and disk, we now ack any
2719
        // Settle/Fails in the mailbox to ensure they do not get redelivered
2720
        // after startup. If forgive is enabled and we've reached this point,
2721
        // the circuits must have been removed at some point, so it is now safe
2722
        // to un-queue the corresponding Settle/Fails.
2723
        for _, inKey := range l.closedCircuits {
8✔
2724
                l.log.Debugf("removing Fail/Settle packet %s from mailbox",
4✔
2725
                        inKey)
4✔
2726
                l.mailBox.AckPacket(inKey)
4✔
2727
        }
4✔
2728

2729
        // Lastly, reset our buffers to be empty while keeping any acquired
2730
        // growth in the backing array.
2731
        l.openedCircuits = l.openedCircuits[:0]
4✔
2732
        l.closedCircuits = l.closedCircuits[:0]
4✔
2733

4✔
2734
        return nil
4✔
2735
}
2736

2737
// updateCommitTxOrFail updates the commitment tx and if that fails, it fails
2738
// the link.
2739
func (l *channelLink) updateCommitTxOrFail(ctx context.Context) bool {
4✔
2740
        err := l.updateCommitTx(ctx)
4✔
2741
        switch err {
4✔
2742
        // No error encountered, success.
2743
        case nil:
4✔
2744

2745
        // A duplicate keystone error should be resolved and is not fatal, so
2746
        // we won't send an Error message to the peer.
2747
        case ErrDuplicateKeystone:
×
2748
                l.failf(LinkFailureError{code: ErrCircuitError},
×
2749
                        "temporary circuit error: %v", err)
×
2750
                return false
×
2751

2752
        // Any other error is treated results in an Error message being sent to
2753
        // the peer.
2754
        default:
×
2755
                l.failf(LinkFailureError{code: ErrInternalError},
×
2756
                        "unable to update commitment: %v", err)
×
2757
                return false
×
2758
        }
2759

2760
        return true
4✔
2761
}
2762

2763
// updateCommitTx signs, then sends an update to the remote peer adding a new
2764
// commitment to their commitment chain which includes all the latest updates
2765
// we've received+processed up to this point.
2766
func (l *channelLink) updateCommitTx(ctx context.Context) error {
4✔
2767
        // Preemptively write all pending keystones to disk, just in case the
4✔
2768
        // HTLCs we have in memory are included in the subsequent attempt to
4✔
2769
        // sign a commitment state.
4✔
2770
        err := l.cfg.Circuits.OpenCircuits(l.keystoneBatch...)
4✔
2771
        if err != nil {
4✔
2772
                // If ErrDuplicateKeystone is returned, the caller will catch
×
2773
                // it.
×
2774
                return err
×
2775
        }
×
2776

2777
        // Reset the batch, but keep the backing buffer to avoid reallocating.
2778
        l.keystoneBatch = l.keystoneBatch[:0]
4✔
2779

4✔
2780
        // If hodl.Commit mode is active, we will refrain from attempting to
4✔
2781
        // commit any in-memory modifications to the channel state. Exiting here
4✔
2782
        // permits testing of either the switch or link's ability to trim
4✔
2783
        // circuits that have been opened, but unsuccessfully committed.
4✔
2784
        if l.cfg.HodlMask.Active(hodl.Commit) {
8✔
2785
                l.log.Warnf(hodl.Commit.Warning())
4✔
2786
                return nil
4✔
2787
        }
4✔
2788

2789
        ctx, done := l.cg.WithCtx(ctx)
4✔
2790
        defer done()
4✔
2791

4✔
2792
        newCommit, err := l.channel.SignNextCommitment(ctx)
4✔
2793
        if err == lnwallet.ErrNoWindow {
8✔
2794
                l.cfg.PendingCommitTicker.Resume()
4✔
2795
                l.log.Trace("PendingCommitTicker resumed")
4✔
2796

4✔
2797
                n := l.channel.NumPendingUpdates(lntypes.Local, lntypes.Remote)
4✔
2798
                l.log.Tracef("revocation window exhausted, unable to send: "+
4✔
2799
                        "%v, pend_updates=%v, dangling_closes%v", n,
4✔
2800
                        lnutils.SpewLogClosure(l.openedCircuits),
4✔
2801
                        lnutils.SpewLogClosure(l.closedCircuits))
4✔
2802

4✔
2803
                return nil
4✔
2804
        } else if err != nil {
9✔
2805
                return err
1✔
2806
        }
1✔
2807

2808
        if err := l.ackDownStreamPackets(); err != nil {
4✔
2809
                return err
×
2810
        }
×
2811

2812
        l.cfg.PendingCommitTicker.Pause()
4✔
2813
        l.log.Trace("PendingCommitTicker paused after ackDownStreamPackets")
4✔
2814

4✔
2815
        // The remote party now has a new pending commitment, so we'll update
4✔
2816
        // the contract court to be aware of this new set (the prior old remote
4✔
2817
        // pending).
4✔
2818
        newUpdate := &contractcourt.ContractUpdate{
4✔
2819
                HtlcKey: contractcourt.RemotePendingHtlcSet,
4✔
2820
                Htlcs:   newCommit.PendingHTLCs,
4✔
2821
        }
4✔
2822
        err = l.cfg.NotifyContractUpdate(newUpdate)
4✔
2823
        if err != nil {
4✔
2824
                l.log.Errorf("unable to notify contract update: %v", err)
×
2825
                return err
×
2826
        }
×
2827

2828
        select {
4✔
NEW
2829
        case <-l.cg.Done():
×
2830
                return ErrLinkShuttingDown
×
2831
        default:
4✔
2832
        }
2833

2834
        auxBlobRecords, err := lnwire.ParseCustomRecords(newCommit.AuxSigBlob)
4✔
2835
        if err != nil {
4✔
2836
                return fmt.Errorf("error parsing aux sigs: %w", err)
×
2837
        }
×
2838

2839
        commitSig := &lnwire.CommitSig{
4✔
2840
                ChanID:        l.ChanID(),
4✔
2841
                CommitSig:     newCommit.CommitSig,
4✔
2842
                HtlcSigs:      newCommit.HtlcSigs,
4✔
2843
                PartialSig:    newCommit.PartialSig,
4✔
2844
                CustomRecords: auxBlobRecords,
4✔
2845
        }
4✔
2846
        l.cfg.Peer.SendMessage(false, commitSig)
4✔
2847

4✔
2848
        // Now that we have sent out a new CommitSig, we invoke the outgoing set
4✔
2849
        // of commit hooks.
4✔
2850
        l.RWMutex.Lock()
4✔
2851
        l.outgoingCommitHooks.invoke()
4✔
2852
        l.RWMutex.Unlock()
4✔
2853

4✔
2854
        return nil
4✔
2855
}
2856

2857
// Peer returns the representation of remote peer with which we have the
2858
// channel link opened.
2859
//
2860
// NOTE: Part of the ChannelLink interface.
2861
func (l *channelLink) PeerPubKey() [33]byte {
4✔
2862
        return l.cfg.Peer.PubKey()
4✔
2863
}
4✔
2864

2865
// ChannelPoint returns the channel outpoint for the channel link.
2866
// NOTE: Part of the ChannelLink interface.
2867
func (l *channelLink) ChannelPoint() wire.OutPoint {
4✔
2868
        return l.channel.ChannelPoint()
4✔
2869
}
4✔
2870

2871
// ShortChanID returns the short channel ID for the channel link. The short
2872
// channel ID encodes the exact location in the main chain that the original
2873
// funding output can be found.
2874
//
2875
// NOTE: Part of the ChannelLink interface.
2876
func (l *channelLink) ShortChanID() lnwire.ShortChannelID {
4✔
2877
        l.RLock()
4✔
2878
        defer l.RUnlock()
4✔
2879

4✔
2880
        return l.channel.ShortChanID()
4✔
2881
}
4✔
2882

2883
// UpdateShortChanID updates the short channel ID for a link. This may be
2884
// required in the event that a link is created before the short chan ID for it
2885
// is known, or a re-org occurs, and the funding transaction changes location
2886
// within the chain.
2887
//
2888
// NOTE: Part of the ChannelLink interface.
2889
func (l *channelLink) UpdateShortChanID() (lnwire.ShortChannelID, error) {
4✔
2890
        chanID := l.ChanID()
4✔
2891

4✔
2892
        // Refresh the channel state's short channel ID by loading it from disk.
4✔
2893
        // This ensures that the channel state accurately reflects the updated
4✔
2894
        // short channel ID.
4✔
2895
        err := l.channel.State().Refresh()
4✔
2896
        if err != nil {
4✔
2897
                l.log.Errorf("unable to refresh short_chan_id for chan_id=%v: "+
×
2898
                        "%v", chanID, err)
×
2899
                return hop.Source, err
×
2900
        }
×
2901

2902
        return hop.Source, nil
4✔
2903
}
2904

2905
// ChanID returns the channel ID for the channel link. The channel ID is a more
2906
// compact representation of a channel's full outpoint.
2907
//
2908
// NOTE: Part of the ChannelLink interface.
2909
func (l *channelLink) ChanID() lnwire.ChannelID {
4✔
2910
        return lnwire.NewChanIDFromOutPoint(l.channel.ChannelPoint())
4✔
2911
}
4✔
2912

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

2926
// MayAddOutgoingHtlc indicates whether we can add an outgoing htlc with the
2927
// amount provided to the link. This check does not reserve a space, since
2928
// forwards or other payments may use the available slot, so it should be
2929
// considered best-effort.
2930
func (l *channelLink) MayAddOutgoingHtlc(amt lnwire.MilliSatoshi) error {
4✔
2931
        return l.channel.MayAddOutgoingHtlc(amt)
4✔
2932
}
4✔
2933

2934
// getDustSum is a wrapper method that calls the underlying channel's dust sum
2935
// method.
2936
//
2937
// NOTE: Part of the dustHandler interface.
2938
func (l *channelLink) getDustSum(whoseCommit lntypes.ChannelParty,
2939
        dryRunFee fn.Option[chainfee.SatPerKWeight]) lnwire.MilliSatoshi {
4✔
2940

4✔
2941
        return l.channel.GetDustSum(whoseCommit, dryRunFee)
4✔
2942
}
4✔
2943

2944
// getFeeRate is a wrapper method that retrieves the underlying channel's
2945
// feerate.
2946
//
2947
// NOTE: Part of the dustHandler interface.
2948
func (l *channelLink) getFeeRate() chainfee.SatPerKWeight {
4✔
2949
        return l.channel.CommitFeeRate()
4✔
2950
}
4✔
2951

2952
// getDustClosure returns a closure that can be used by the switch or mailbox
2953
// to evaluate whether a given HTLC is dust.
2954
//
2955
// NOTE: Part of the dustHandler interface.
2956
func (l *channelLink) getDustClosure() dustClosure {
4✔
2957
        localDustLimit := l.channel.State().LocalChanCfg.DustLimit
4✔
2958
        remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit
4✔
2959
        chanType := l.channel.State().ChanType
4✔
2960

4✔
2961
        return dustHelper(chanType, localDustLimit, remoteDustLimit)
4✔
2962
}
4✔
2963

2964
// getCommitFee returns either the local or remote CommitFee in satoshis. This
2965
// is used so that the Switch can have access to the commitment fee without
2966
// needing to have a *LightningChannel. This doesn't include dust.
2967
//
2968
// NOTE: Part of the dustHandler interface.
2969
func (l *channelLink) getCommitFee(remote bool) btcutil.Amount {
4✔
2970
        if remote {
8✔
2971
                return l.channel.State().RemoteCommitment.CommitFee
4✔
2972
        }
4✔
2973

2974
        return l.channel.State().LocalCommitment.CommitFee
4✔
2975
}
2976

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

×
2991
        dryRunFee := fn.Some[chainfee.SatPerKWeight](feePerKw)
×
2992

×
2993
        // Get the sum of dust for both the local and remote commitments using
×
2994
        // this "dry-run" fee.
×
2995
        localDustSum := l.getDustSum(lntypes.Local, dryRunFee)
×
2996
        remoteDustSum := l.getDustSum(lntypes.Remote, dryRunFee)
×
2997

×
2998
        // Calculate the local and remote commitment fees using this dry-run
×
2999
        // fee.
×
3000
        localFee, remoteFee, err := l.channel.CommitFeeTotalAt(feePerKw)
×
3001
        if err != nil {
×
3002
                return false, err
×
3003
        }
×
3004

3005
        // Finally, check whether the max fee exposure was exceeded on either
3006
        // future commitment transaction with the fee-rate.
3007
        totalLocalDust := localDustSum + lnwire.NewMSatFromSatoshis(localFee)
×
3008
        if totalLocalDust > l.cfg.MaxFeeExposure {
×
3009
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
3010
                        "local dust: %v, local fee: %v", l.ShortChanID(),
×
3011
                        totalLocalDust, localFee)
×
3012

×
3013
                return true, nil
×
3014
        }
×
3015

3016
        totalRemoteDust := remoteDustSum + lnwire.NewMSatFromSatoshis(
×
3017
                remoteFee,
×
3018
        )
×
3019

×
3020
        if totalRemoteDust > l.cfg.MaxFeeExposure {
×
3021
                l.log.Debugf("ChannelLink(%v): exceeds fee exposure limit: "+
×
3022
                        "remote dust: %v, remote fee: %v", l.ShortChanID(),
×
3023
                        totalRemoteDust, remoteFee)
×
3024

×
3025
                return true, nil
×
3026
        }
×
3027

3028
        return false, nil
×
3029
}
3030

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

4✔
3042
        dustClosure := l.getDustClosure()
4✔
3043

4✔
3044
        feeRate := l.channel.WorstCaseFeeRate()
4✔
3045

4✔
3046
        amount := htlc.Amount.ToSatoshis()
4✔
3047

4✔
3048
        // See if this HTLC is dust on both the local and remote commitments.
4✔
3049
        isLocalDust := dustClosure(feeRate, incoming, lntypes.Local, amount)
4✔
3050
        isRemoteDust := dustClosure(feeRate, incoming, lntypes.Remote, amount)
4✔
3051

4✔
3052
        // Calculate the dust sum for the local and remote commitments.
4✔
3053
        localDustSum := l.getDustSum(
4✔
3054
                lntypes.Local, fn.None[chainfee.SatPerKWeight](),
4✔
3055
        )
4✔
3056
        remoteDustSum := l.getDustSum(
4✔
3057
                lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
4✔
3058
        )
4✔
3059

4✔
3060
        // Grab the larger of the local and remote commitment fees w/o dust.
4✔
3061
        commitFee := l.getCommitFee(false)
4✔
3062

4✔
3063
        if l.getCommitFee(true) > commitFee {
8✔
3064
                commitFee = l.getCommitFee(true)
4✔
3065
        }
4✔
3066

3067
        commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)
4✔
3068

4✔
3069
        localDustSum += commitFeeMSat
4✔
3070
        remoteDustSum += commitFeeMSat
4✔
3071

4✔
3072
        // Calculate the additional fee increase if this is a non-dust HTLC.
4✔
3073
        weight := lntypes.WeightUnit(input.HTLCWeight)
4✔
3074
        additional := lnwire.NewMSatFromSatoshis(
4✔
3075
                feeRate.FeeForWeight(weight),
4✔
3076
        )
4✔
3077

4✔
3078
        if isLocalDust {
8✔
3079
                // If this is dust, it doesn't contribute to weight but does
4✔
3080
                // contribute to the overall dust sum.
4✔
3081
                localDustSum += lnwire.NewMSatFromSatoshis(amount)
4✔
3082
        } else {
8✔
3083
                // Account for the fee increase that comes with an increase in
4✔
3084
                // weight.
4✔
3085
                localDustSum += additional
4✔
3086
        }
4✔
3087

3088
        if localDustSum > l.cfg.MaxFeeExposure {
4✔
3089
                // The max fee exposure was exceeded.
×
3090
                l.log.Debugf("ChannelLink(%v): HTLC %v makes the channel "+
×
3091
                        "overexposed, total local dust: %v (current commit "+
×
3092
                        "fee: %v)", l.ShortChanID(), htlc, localDustSum)
×
3093

×
3094
                return true
×
3095
        }
×
3096

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

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

×
3113
                return true
×
3114
        }
×
3115

3116
        return false
4✔
3117
}
3118

3119
// dustClosure is a function that evaluates whether an HTLC is dust. It returns
3120
// true if the HTLC is dust. It takes in a feerate, a boolean denoting whether
3121
// the HTLC is incoming (i.e. one that the remote sent), a boolean denoting
3122
// whether to evaluate on the local or remote commit, and finally an HTLC
3123
// amount to test.
3124
type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool,
3125
        whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool
3126

3127
// dustHelper is used to construct the dustClosure.
3128
func dustHelper(chantype channeldb.ChannelType, localDustLimit,
3129
        remoteDustLimit btcutil.Amount) dustClosure {
4✔
3130

4✔
3131
        isDust := func(feerate chainfee.SatPerKWeight, incoming bool,
4✔
3132
                whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool {
8✔
3133

4✔
3134
                var dustLimit btcutil.Amount
4✔
3135
                if whoseCommit.IsLocal() {
8✔
3136
                        dustLimit = localDustLimit
4✔
3137
                } else {
8✔
3138
                        dustLimit = remoteDustLimit
4✔
3139
                }
4✔
3140

3141
                return lnwallet.HtlcIsDust(
4✔
3142
                        chantype, incoming, whoseCommit, feerate, amt,
4✔
3143
                        dustLimit,
4✔
3144
                )
4✔
3145
        }
3146

3147
        return isDust
4✔
3148
}
3149

3150
// zeroConfConfirmed returns whether or not the zero-conf channel has
3151
// confirmed on-chain.
3152
//
3153
// Part of the scidAliasHandler interface.
3154
func (l *channelLink) zeroConfConfirmed() bool {
4✔
3155
        return l.channel.State().ZeroConfConfirmed()
4✔
3156
}
4✔
3157

3158
// confirmedScid returns the confirmed SCID for a zero-conf channel. This
3159
// should not be called for non-zero-conf channels.
3160
//
3161
// Part of the scidAliasHandler interface.
3162
func (l *channelLink) confirmedScid() lnwire.ShortChannelID {
4✔
3163
        return l.channel.State().ZeroConfRealScid()
4✔
3164
}
4✔
3165

3166
// isZeroConf returns whether or not the underlying channel is a zero-conf
3167
// channel.
3168
//
3169
// Part of the scidAliasHandler interface.
3170
func (l *channelLink) isZeroConf() bool {
4✔
3171
        return l.channel.State().IsZeroConf()
4✔
3172
}
4✔
3173

3174
// negotiatedAliasFeature returns whether or not the underlying channel has
3175
// negotiated the option-scid-alias feature bit. This will be true for both
3176
// option-scid-alias and zero-conf channel-types. It will also be true for
3177
// channels with the feature bit but without the above channel-types.
3178
//
3179
// Part of the scidAliasFeature interface.
3180
func (l *channelLink) negotiatedAliasFeature() bool {
4✔
3181
        return l.channel.State().NegotiatedAliasFeature()
4✔
3182
}
4✔
3183

3184
// getAliases returns the set of aliases for the underlying channel.
3185
//
3186
// Part of the scidAliasHandler interface.
3187
func (l *channelLink) getAliases() []lnwire.ShortChannelID {
4✔
3188
        return l.cfg.GetAliases(l.ShortChanID())
4✔
3189
}
4✔
3190

3191
// attachFailAliasUpdate sets the link's FailAliasUpdate function.
3192
//
3193
// Part of the scidAliasHandler interface.
3194
func (l *channelLink) attachFailAliasUpdate(closure func(
3195
        sid lnwire.ShortChannelID, incoming bool) *lnwire.ChannelUpdate1) {
4✔
3196

4✔
3197
        l.Lock()
4✔
3198
        l.cfg.FailAliasUpdate = closure
4✔
3199
        l.Unlock()
4✔
3200
}
4✔
3201

3202
// AttachMailBox updates the current mailbox used by this link, and hooks up
3203
// the mailbox's message and packet outboxes to the link's upstream and
3204
// downstream chans, respectively.
3205
func (l *channelLink) AttachMailBox(mailbox MailBox) {
4✔
3206
        l.Lock()
4✔
3207
        l.mailBox = mailbox
4✔
3208
        l.upstream = mailbox.MessageOutBox()
4✔
3209
        l.downstream = mailbox.PacketOutBox()
4✔
3210
        l.Unlock()
4✔
3211

4✔
3212
        // Set the mailbox's fee rate. This may be refreshing a feerate that was
4✔
3213
        // never committed.
4✔
3214
        l.mailBox.SetFeeRate(l.getFeeRate())
4✔
3215

4✔
3216
        // Also set the mailbox's dust closure so that it can query whether HTLC's
4✔
3217
        // are dust given the current feerate.
4✔
3218
        l.mailBox.SetDustClosure(l.getDustClosure())
4✔
3219
}
4✔
3220

3221
// UpdateForwardingPolicy updates the forwarding policy for the target
3222
// ChannelLink. Once updated, the link will use the new forwarding policy to
3223
// govern if it an incoming HTLC should be forwarded or not. We assume that
3224
// fields that are zero are intentionally set to zero, so we'll use newPolicy to
3225
// update all of the link's FwrdingPolicy's values.
3226
//
3227
// NOTE: Part of the ChannelLink interface.
3228
func (l *channelLink) UpdateForwardingPolicy(
3229
        newPolicy models.ForwardingPolicy) {
4✔
3230

4✔
3231
        l.Lock()
4✔
3232
        defer l.Unlock()
4✔
3233

4✔
3234
        l.cfg.FwrdingPolicy = newPolicy
4✔
3235
}
4✔
3236

3237
// CheckHtlcForward should return a nil error if the passed HTLC details
3238
// satisfy the current forwarding policy fo the target link. Otherwise,
3239
// a LinkError with a valid protocol failure message should be returned
3240
// in order to signal to the source of the HTLC, the policy consistency
3241
// issue.
3242
//
3243
// NOTE: Part of the ChannelLink interface.
3244
func (l *channelLink) CheckHtlcForward(payHash [32]byte, incomingHtlcAmt,
3245
        amtToForward lnwire.MilliSatoshi, incomingTimeout,
3246
        outgoingTimeout uint32, inboundFee models.InboundFee,
3247
        heightNow uint32, originalScid lnwire.ShortChannelID,
3248
        customRecords lnwire.CustomRecords) *LinkError {
4✔
3249

4✔
3250
        l.RLock()
4✔
3251
        policy := l.cfg.FwrdingPolicy
4✔
3252
        l.RUnlock()
4✔
3253

4✔
3254
        // Using the outgoing HTLC amount, we'll calculate the outgoing
4✔
3255
        // fee this incoming HTLC must carry in order to satisfy the constraints
4✔
3256
        // of the outgoing link.
4✔
3257
        outFee := ExpectedFee(policy, amtToForward)
4✔
3258

4✔
3259
        // Then calculate the inbound fee that we charge based on the sum of
4✔
3260
        // outgoing HTLC amount and outgoing fee.
4✔
3261
        inFee := inboundFee.CalcFee(amtToForward + outFee)
4✔
3262

4✔
3263
        // Add up both fee components. It is important to calculate both fees
4✔
3264
        // separately. An alternative way of calculating is to first determine
4✔
3265
        // an aggregate fee and apply that to the outgoing HTLC amount. However,
4✔
3266
        // rounding may cause the result to be slightly higher than in the case
4✔
3267
        // of separately rounded fee components. This potentially causes failed
4✔
3268
        // forwards for senders and is something to be avoided.
4✔
3269
        expectedFee := inFee + int64(outFee)
4✔
3270

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

4✔
3285
                // As part of the returned error, we'll send our latest routing
4✔
3286
                // policy so the sending node obtains the most up to date data.
4✔
3287
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
3288
                        return lnwire.NewFeeInsufficient(amtToForward, *upd)
4✔
3289
                }
4✔
3290
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
3291
                return NewLinkError(failure)
4✔
3292
        }
3293

3294
        // Check whether the outgoing htlc satisfies the channel policy.
3295
        err := l.canSendHtlc(
4✔
3296
                policy, payHash, amtToForward, outgoingTimeout, heightNow,
4✔
3297
                originalScid, customRecords,
4✔
3298
        )
4✔
3299
        if err != nil {
8✔
3300
                return err
4✔
3301
        }
4✔
3302

3303
        // Finally, we'll ensure that the time-lock on the outgoing HTLC meets
3304
        // the following constraint: the incoming time-lock minus our time-lock
3305
        // delta should equal the outgoing time lock. Otherwise, whether the
3306
        // sender messed up, or an intermediate node tampered with the HTLC.
3307
        timeDelta := policy.TimeLockDelta
4✔
3308
        if incomingTimeout < outgoingTimeout+timeDelta {
4✔
3309
                l.log.Warnf("incoming htlc(%x) has incorrect time-lock value: "+
×
3310
                        "expected at least %v block delta, got %v block delta",
×
3311
                        payHash[:], timeDelta, incomingTimeout-outgoingTimeout)
×
3312

×
3313
                // Grab the latest routing policy so the sending node is up to
×
3314
                // date with our current policy.
×
3315
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
×
3316
                        return lnwire.NewIncorrectCltvExpiry(
×
3317
                                incomingTimeout, *upd,
×
3318
                        )
×
3319
                }
×
3320
                failure := l.createFailureWithUpdate(false, originalScid, cb)
×
3321
                return NewLinkError(failure)
×
3322
        }
3323

3324
        return nil
4✔
3325
}
3326

3327
// CheckHtlcTransit should return a nil error if the passed HTLC details
3328
// satisfy the current channel policy.  Otherwise, a LinkError with a
3329
// valid protocol failure message should be returned in order to signal
3330
// the violation. This call is intended to be used for locally initiated
3331
// payments for which there is no corresponding incoming htlc.
3332
func (l *channelLink) CheckHtlcTransit(payHash [32]byte,
3333
        amt lnwire.MilliSatoshi, timeout uint32, heightNow uint32,
3334
        customRecords lnwire.CustomRecords) *LinkError {
4✔
3335

4✔
3336
        l.RLock()
4✔
3337
        policy := l.cfg.FwrdingPolicy
4✔
3338
        l.RUnlock()
4✔
3339

4✔
3340
        // We pass in hop.Source here as this is only used in the Switch when
4✔
3341
        // trying to send over a local link. This causes the fallback mechanism
4✔
3342
        // to occur.
4✔
3343
        return l.canSendHtlc(
4✔
3344
                policy, payHash, amt, timeout, heightNow, hop.Source,
4✔
3345
                customRecords,
4✔
3346
        )
4✔
3347
}
4✔
3348

3349
// canSendHtlc checks whether the given htlc parameters satisfy
3350
// the channel's amount and time lock constraints.
3351
func (l *channelLink) canSendHtlc(policy models.ForwardingPolicy,
3352
        payHash [32]byte, amt lnwire.MilliSatoshi, timeout uint32,
3353
        heightNow uint32, originalScid lnwire.ShortChannelID,
3354
        customRecords lnwire.CustomRecords) *LinkError {
4✔
3355

4✔
3356
        // As our first sanity check, we'll ensure that the passed HTLC isn't
4✔
3357
        // too small for the next hop. If so, then we'll cancel the HTLC
4✔
3358
        // directly.
4✔
3359
        if amt < policy.MinHTLCOut {
8✔
3360
                l.log.Warnf("outgoing htlc(%x) is too small: min_htlc=%v, "+
4✔
3361
                        "htlc_value=%v", payHash[:], policy.MinHTLCOut,
4✔
3362
                        amt)
4✔
3363

4✔
3364
                // As part of the returned error, we'll send our latest routing
4✔
3365
                // policy so the sending node obtains the most up to date data.
4✔
3366
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
3367
                        return lnwire.NewAmountBelowMinimum(amt, *upd)
4✔
3368
                }
4✔
3369
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
3370
                return NewLinkError(failure)
4✔
3371
        }
3372

3373
        // Next, ensure that the passed HTLC isn't too large. If so, we'll
3374
        // cancel the HTLC directly.
3375
        if policy.MaxHTLC != 0 && amt > policy.MaxHTLC {
8✔
3376
                l.log.Warnf("outgoing htlc(%x) is too large: max_htlc=%v, "+
4✔
3377
                        "htlc_value=%v", payHash[:], policy.MaxHTLC, amt)
4✔
3378

4✔
3379
                // As part of the returned error, we'll send our latest routing
4✔
3380
                // policy so the sending node obtains the most up-to-date data.
4✔
3381
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
3382
                        return lnwire.NewTemporaryChannelFailure(upd)
4✔
3383
                }
4✔
3384
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
3385
                return NewDetailedLinkError(failure, OutgoingFailureHTLCExceedsMax)
4✔
3386
        }
3387

3388
        // We want to avoid offering an HTLC which will expire in the near
3389
        // future, so we'll reject an HTLC if the outgoing expiration time is
3390
        // too close to the current height.
3391
        if timeout <= heightNow+l.cfg.OutgoingCltvRejectDelta {
4✔
3392
                l.log.Warnf("htlc(%x) has an expiry that's too soon: "+
×
3393
                        "outgoing_expiry=%v, best_height=%v", payHash[:],
×
3394
                        timeout, heightNow)
×
3395

×
3396
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
×
3397
                        return lnwire.NewExpiryTooSoon(*upd)
×
3398
                }
×
3399
                failure := l.createFailureWithUpdate(false, originalScid, cb)
×
3400
                return NewLinkError(failure)
×
3401
        }
3402

3403
        // Check absolute max delta.
3404
        if timeout > l.cfg.MaxOutgoingCltvExpiry+heightNow {
4✔
3405
                l.log.Warnf("outgoing htlc(%x) has a time lock too far in "+
×
3406
                        "the future: got %v, but maximum is %v", payHash[:],
×
3407
                        timeout-heightNow, l.cfg.MaxOutgoingCltvExpiry)
×
3408

×
3409
                return NewLinkError(&lnwire.FailExpiryTooFar{})
×
3410
        }
×
3411

3412
        // We now check the available bandwidth to see if this HTLC can be
3413
        // forwarded.
3414
        availableBandwidth := l.Bandwidth()
4✔
3415
        auxBandwidth, err := fn.MapOptionZ(
4✔
3416
                l.cfg.AuxTrafficShaper,
4✔
3417
                func(ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
4✔
3418
                        var htlcBlob fn.Option[tlv.Blob]
×
3419
                        blob, err := customRecords.Serialize()
×
3420
                        if err != nil {
×
3421
                                return fn.Err[OptionalBandwidth](
×
3422
                                        fmt.Errorf("unable to serialize "+
×
3423
                                                "custom records: %w", err))
×
3424
                        }
×
3425

3426
                        if len(blob) > 0 {
×
3427
                                htlcBlob = fn.Some(blob)
×
3428
                        }
×
3429

3430
                        return l.AuxBandwidth(amt, originalScid, htlcBlob, ts)
×
3431
                },
3432
        ).Unpack()
3433
        if err != nil {
4✔
3434
                l.log.Errorf("Unable to determine aux bandwidth: %v", err)
×
3435
                return NewLinkError(&lnwire.FailTemporaryNodeFailure{})
×
3436
        }
×
3437

3438
        auxBandwidth.WhenSome(func(bandwidth lnwire.MilliSatoshi) {
4✔
3439
                availableBandwidth = bandwidth
×
3440
        })
×
3441

3442
        // Check to see if there is enough balance in this channel.
3443
        if amt > availableBandwidth {
8✔
3444
                l.log.Warnf("insufficient bandwidth to route htlc: %v is "+
4✔
3445
                        "larger than %v", amt, l.Bandwidth())
4✔
3446
                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage {
8✔
3447
                        return lnwire.NewTemporaryChannelFailure(upd)
4✔
3448
                }
4✔
3449
                failure := l.createFailureWithUpdate(false, originalScid, cb)
4✔
3450
                return NewDetailedLinkError(
4✔
3451
                        failure, OutgoingFailureInsufficientBalance,
4✔
3452
                )
4✔
3453
        }
3454

3455
        return nil
4✔
3456
}
3457

3458
// AuxBandwidth returns the bandwidth that can be used for a channel, expressed
3459
// in milli-satoshi. This might be different from the regular BTC bandwidth for
3460
// custom channels. This will always return fn.None() for a regular (non-custom)
3461
// channel.
3462
func (l *channelLink) AuxBandwidth(amount lnwire.MilliSatoshi,
3463
        cid lnwire.ShortChannelID, htlcBlob fn.Option[tlv.Blob],
3464
        ts AuxTrafficShaper) fn.Result[OptionalBandwidth] {
×
3465

×
3466
        unknownBandwidth := fn.None[lnwire.MilliSatoshi]()
×
3467

×
3468
        fundingBlob := l.FundingCustomBlob()
×
3469
        shouldHandle, err := ts.ShouldHandleTraffic(cid, fundingBlob)
×
3470
        if err != nil {
×
3471
                return fn.Err[OptionalBandwidth](fmt.Errorf("traffic shaper "+
×
3472
                        "failed to decide whether to handle traffic: %w", err))
×
3473
        }
×
3474

3475
        log.Debugf("ShortChannelID=%v: aux traffic shaper is handling "+
×
3476
                "traffic: %v", cid, shouldHandle)
×
3477

×
3478
        // If this channel isn't handled by the aux traffic shaper, we'll return
×
3479
        // early.
×
3480
        if !shouldHandle {
×
3481
                return fn.Ok(unknownBandwidth)
×
3482
        }
×
3483

3484
        // Ask for a specific bandwidth to be used for the channel.
3485
        commitmentBlob := l.CommitmentCustomBlob()
×
3486
        auxBandwidth, err := ts.PaymentBandwidth(
×
3487
                htlcBlob, commitmentBlob, l.Bandwidth(), amount,
×
3488
        )
×
3489
        if err != nil {
×
3490
                return fn.Err[OptionalBandwidth](fmt.Errorf("failed to get "+
×
3491
                        "bandwidth from external traffic shaper: %w", err))
×
3492
        }
×
3493

3494
        log.Debugf("ShortChannelID=%v: aux traffic shaper reported available "+
×
3495
                "bandwidth: %v", cid, auxBandwidth)
×
3496

×
3497
        return fn.Ok(fn.Some(auxBandwidth))
×
3498
}
3499

3500
// Stats returns the statistics of channel link.
3501
//
3502
// NOTE: Part of the ChannelLink interface.
3503
func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
4✔
3504
        snapshot := l.channel.StateSnapshot()
4✔
3505

4✔
3506
        return snapshot.ChannelCommitment.CommitHeight,
4✔
3507
                snapshot.TotalMSatSent,
4✔
3508
                snapshot.TotalMSatReceived
4✔
3509
}
4✔
3510

3511
// String returns the string representation of channel link.
3512
//
3513
// NOTE: Part of the ChannelLink interface.
3514
func (l *channelLink) String() string {
×
3515
        return l.channel.ChannelPoint().String()
×
3516
}
×
3517

3518
// handleSwitchPacket handles the switch packets. This packets which might be
3519
// forwarded to us from another channel link in case the htlc update came from
3520
// another peer or if the update was created by user
3521
//
3522
// NOTE: Part of the packetHandler interface.
3523
func (l *channelLink) handleSwitchPacket(pkt *htlcPacket) error {
4✔
3524
        l.log.Tracef("received switch packet inkey=%v, outkey=%v",
4✔
3525
                pkt.inKey(), pkt.outKey())
4✔
3526

4✔
3527
        return l.mailBox.AddPacket(pkt)
4✔
3528
}
4✔
3529

3530
// HandleChannelUpdate handles the htlc requests as settle/add/fail which sent
3531
// to us from remote peer we have a channel with.
3532
//
3533
// NOTE: Part of the ChannelLink interface.
3534
func (l *channelLink) HandleChannelUpdate(message lnwire.Message) {
4✔
3535
        select {
4✔
NEW
3536
        case <-l.cg.Done():
×
3537
                // Return early if the link is already in the process of
×
3538
                // quitting. It doesn't make sense to hand the message to the
×
3539
                // mailbox here.
×
3540
                return
×
3541
        default:
4✔
3542
        }
3543

3544
        err := l.mailBox.AddMessage(message)
4✔
3545
        if err != nil {
4✔
3546
                l.log.Errorf("failed to add Message to mailbox: %v", err)
×
3547
        }
×
3548
}
3549

3550
// updateChannelFee updates the commitment fee-per-kw on this channel by
3551
// committing to an update_fee message.
3552
func (l *channelLink) updateChannelFee(ctx context.Context,
NEW
3553
        feePerKw chainfee.SatPerKWeight) error {
×
NEW
3554

×
3555
        l.log.Infof("updating commit fee to %v", feePerKw)
×
3556

×
3557
        // We skip sending the UpdateFee message if the channel is not
×
3558
        // currently eligible to forward messages.
×
3559
        if !l.eligibleToUpdate() {
×
3560
                l.log.Debugf("skipping fee update for inactive channel")
×
3561
                return nil
×
3562
        }
×
3563

3564
        // Check and see if our proposed fee-rate would make us exceed the fee
3565
        // threshold.
3566
        thresholdExceeded, err := l.exceedsFeeExposureLimit(feePerKw)
×
3567
        if err != nil {
×
3568
                // This shouldn't typically happen. If it does, it indicates
×
3569
                // something is wrong with our channel state.
×
3570
                return err
×
3571
        }
×
3572

3573
        if thresholdExceeded {
×
3574
                return fmt.Errorf("link fee threshold exceeded")
×
3575
        }
×
3576

3577
        // First, we'll update the local fee on our commitment.
3578
        if err := l.channel.UpdateFee(feePerKw); err != nil {
×
3579
                return err
×
3580
        }
×
3581

3582
        // The fee passed the channel's validation checks, so we update the
3583
        // mailbox feerate.
3584
        l.mailBox.SetFeeRate(feePerKw)
×
3585

×
3586
        // We'll then attempt to send a new UpdateFee message, and also lock it
×
3587
        // in immediately by triggering a commitment update.
×
3588
        msg := lnwire.NewUpdateFee(l.ChanID(), uint32(feePerKw))
×
3589
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
×
3590
                return err
×
3591
        }
×
NEW
3592
        return l.updateCommitTx(ctx)
×
3593
}
3594

3595
// processRemoteSettleFails accepts a batch of settle/fail payment descriptors
3596
// after receiving a revocation from the remote party, and reprocesses them in
3597
// the context of the provided forwarding package. Any settles or fails that
3598
// have already been acknowledged in the forwarding package will not be sent to
3599
// the switch.
3600
func (l *channelLink) processRemoteSettleFails(fwdPkg *channeldb.FwdPkg) {
4✔
3601
        if len(fwdPkg.SettleFails) == 0 {
8✔
3602
                return
4✔
3603
        }
4✔
3604

3605
        l.log.Debugf("settle-fail-filter: %v", fwdPkg.SettleFailFilter)
4✔
3606

4✔
3607
        var switchPackets []*htlcPacket
4✔
3608
        for i, update := range fwdPkg.SettleFails {
8✔
3609
                destRef := fwdPkg.DestRef(uint16(i))
4✔
3610

4✔
3611
                // Skip any settles or fails that have already been
4✔
3612
                // acknowledged by the incoming link that originated the
4✔
3613
                // forwarded Add.
4✔
3614
                if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
4✔
3615
                        continue
×
3616
                }
3617

3618
                // TODO(roasbeef): rework log entries to a shared
3619
                // interface.
3620

3621
                switch msg := update.UpdateMsg.(type) {
4✔
3622
                // A settle for an HTLC we previously forwarded HTLC has been
3623
                // received. So we'll forward the HTLC to the switch which will
3624
                // handle propagating the settle to the prior hop.
3625
                case *lnwire.UpdateFulfillHTLC:
4✔
3626
                        // If hodl.SettleIncoming is requested, we will not
4✔
3627
                        // forward the SETTLE to the switch and will not signal
4✔
3628
                        // a free slot on the commitment transaction.
4✔
3629
                        if l.cfg.HodlMask.Active(hodl.SettleIncoming) {
4✔
3630
                                l.log.Warnf(hodl.SettleIncoming.Warning())
×
3631
                                continue
×
3632
                        }
3633

3634
                        settlePacket := &htlcPacket{
4✔
3635
                                outgoingChanID: l.ShortChanID(),
4✔
3636
                                outgoingHTLCID: msg.ID,
4✔
3637
                                destRef:        &destRef,
4✔
3638
                                htlc:           msg,
4✔
3639
                        }
4✔
3640

4✔
3641
                        // Add the packet to the batch to be forwarded, and
4✔
3642
                        // notify the overflow queue that a spare spot has been
4✔
3643
                        // freed up within the commitment state.
4✔
3644
                        switchPackets = append(switchPackets, settlePacket)
4✔
3645

3646
                // A failureCode message for a previously forwarded HTLC has
3647
                // been received. As a result a new slot will be freed up in
3648
                // our commitment state, so we'll forward this to the switch so
3649
                // the backwards undo can continue.
3650
                case *lnwire.UpdateFailHTLC:
4✔
3651
                        // If hodl.SettleIncoming is requested, we will not
4✔
3652
                        // forward the FAIL to the switch and will not signal a
4✔
3653
                        // free slot on the commitment transaction.
4✔
3654
                        if l.cfg.HodlMask.Active(hodl.FailIncoming) {
4✔
3655
                                l.log.Warnf(hodl.FailIncoming.Warning())
×
3656
                                continue
×
3657
                        }
3658

3659
                        // Fetch the reason the HTLC was canceled so we can
3660
                        // continue to propagate it. This failure originated
3661
                        // from another node, so the linkFailure field is not
3662
                        // set on the packet.
3663
                        failPacket := &htlcPacket{
4✔
3664
                                outgoingChanID: l.ShortChanID(),
4✔
3665
                                outgoingHTLCID: msg.ID,
4✔
3666
                                destRef:        &destRef,
4✔
3667
                                htlc:           msg,
4✔
3668
                        }
4✔
3669

4✔
3670
                        l.log.Debugf("Failed to send HTLC with ID=%d", msg.ID)
4✔
3671

4✔
3672
                        // If the failure message lacks an HMAC (but includes
4✔
3673
                        // the 4 bytes for encoding the message and padding
4✔
3674
                        // lengths, then this means that we received it as an
4✔
3675
                        // UpdateFailMalformedHTLC. As a result, we'll signal
4✔
3676
                        // that we need to convert this error within the switch
4✔
3677
                        // to an actual error, by encrypting it as if we were
4✔
3678
                        // the originating hop.
4✔
3679
                        convertedErrorSize := lnwire.FailureMessageLength + 4
4✔
3680
                        if len(msg.Reason) == convertedErrorSize {
8✔
3681
                                failPacket.convertedError = true
4✔
3682
                        }
4✔
3683

3684
                        // Add the packet to the batch to be forwarded, and
3685
                        // notify the overflow queue that a spare spot has been
3686
                        // freed up within the commitment state.
3687
                        switchPackets = append(switchPackets, failPacket)
4✔
3688
                }
3689
        }
3690

3691
        // Only spawn the task forward packets we have a non-zero number.
3692
        if len(switchPackets) > 0 {
8✔
3693
                go l.forwardBatch(false, switchPackets...)
4✔
3694
        }
4✔
3695
}
3696

3697
// processRemoteAdds serially processes each of the Add payment descriptors
3698
// which have been "locked-in" by receiving a revocation from the remote party.
3699
// The forwarding package provided instructs how to process this batch,
3700
// indicating whether this is the first time these Adds are being processed, or
3701
// whether we are reprocessing as a result of a failure or restart. Adds that
3702
// have already been acknowledged in the forwarding package will be ignored.
3703
//
3704
//nolint:funlen
3705
func (l *channelLink) processRemoteAdds(fwdPkg *channeldb.FwdPkg) {
4✔
3706
        l.log.Tracef("processing %d remote adds for height %d",
4✔
3707
                len(fwdPkg.Adds), fwdPkg.Height)
4✔
3708

4✔
3709
        decodeReqs := make(
4✔
3710
                []hop.DecodeHopIteratorRequest, 0, len(fwdPkg.Adds),
4✔
3711
        )
4✔
3712
        for _, update := range fwdPkg.Adds {
8✔
3713
                if msg, ok := update.UpdateMsg.(*lnwire.UpdateAddHTLC); ok {
8✔
3714
                        // Before adding the new htlc to the state machine,
4✔
3715
                        // parse the onion object in order to obtain the
4✔
3716
                        // routing information with DecodeHopIterator function
4✔
3717
                        // which process the Sphinx packet.
4✔
3718
                        onionReader := bytes.NewReader(msg.OnionBlob[:])
4✔
3719

4✔
3720
                        req := hop.DecodeHopIteratorRequest{
4✔
3721
                                OnionReader:    onionReader,
4✔
3722
                                RHash:          msg.PaymentHash[:],
4✔
3723
                                IncomingCltv:   msg.Expiry,
4✔
3724
                                IncomingAmount: msg.Amount,
4✔
3725
                                BlindingPoint:  msg.BlindingPoint,
4✔
3726
                        }
4✔
3727

4✔
3728
                        decodeReqs = append(decodeReqs, req)
4✔
3729
                }
4✔
3730
        }
3731

3732
        // Atomically decode the incoming htlcs, simultaneously checking for
3733
        // replay attempts. A particular index in the returned, spare list of
3734
        // channel iterators should only be used if the failure code at the
3735
        // same index is lnwire.FailCodeNone.
3736
        decodeResps, sphinxErr := l.cfg.DecodeHopIterators(
4✔
3737
                fwdPkg.ID(), decodeReqs,
4✔
3738
        )
4✔
3739
        if sphinxErr != nil {
4✔
3740
                l.failf(LinkFailureError{code: ErrInternalError},
×
3741
                        "unable to decode hop iterators: %v", sphinxErr)
×
3742
                return
×
3743
        }
×
3744

3745
        var switchPackets []*htlcPacket
4✔
3746

4✔
3747
        for i, update := range fwdPkg.Adds {
8✔
3748
                idx := uint16(i)
4✔
3749

4✔
3750
                //nolint:forcetypeassert
4✔
3751
                add := *update.UpdateMsg.(*lnwire.UpdateAddHTLC)
4✔
3752
                sourceRef := fwdPkg.SourceRef(idx)
4✔
3753

4✔
3754
                if fwdPkg.State == channeldb.FwdStateProcessed &&
4✔
3755
                        fwdPkg.AckFilter.Contains(idx) {
4✔
3756

×
3757
                        // If this index is already found in the ack filter,
×
3758
                        // the response to this forwarding decision has already
×
3759
                        // been committed by one of our commitment txns. ADDs
×
3760
                        // in this state are waiting for the rest of the fwding
×
3761
                        // package to get acked before being garbage collected.
×
3762
                        continue
×
3763
                }
3764

3765
                // An incoming HTLC add has been full-locked in. As a result we
3766
                // can now examine the forwarding details of the HTLC, and the
3767
                // HTLC itself to decide if: we should forward it, cancel it,
3768
                // or are able to settle it (and it adheres to our fee related
3769
                // constraints).
3770

3771
                // Before adding the new htlc to the state machine, parse the
3772
                // onion object in order to obtain the routing information with
3773
                // DecodeHopIterator function which process the Sphinx packet.
3774
                chanIterator, failureCode := decodeResps[i].Result()
4✔
3775
                if failureCode != lnwire.CodeNone {
8✔
3776
                        // If we're unable to process the onion blob then we
4✔
3777
                        // should send the malformed htlc error to payment
4✔
3778
                        // sender.
4✔
3779
                        l.sendMalformedHTLCError(
4✔
3780
                                add.ID, failureCode, add.OnionBlob, &sourceRef,
4✔
3781
                        )
4✔
3782

4✔
3783
                        l.log.Errorf("unable to decode onion hop "+
4✔
3784
                                "iterator: %v", failureCode)
4✔
3785
                        continue
4✔
3786
                }
3787

3788
                heightNow := l.cfg.BestHeight()
4✔
3789

4✔
3790
                pld, routeRole, pldErr := chanIterator.HopPayload()
4✔
3791
                if pldErr != nil {
8✔
3792
                        // If we're unable to process the onion payload, or we
4✔
3793
                        // received invalid onion payload failure, then we
4✔
3794
                        // should send an error back to the caller so the HTLC
4✔
3795
                        // can be canceled.
4✔
3796
                        var failedType uint64
4✔
3797

4✔
3798
                        // We need to get the underlying error value, so we
4✔
3799
                        // can't use errors.As as suggested by the linter.
4✔
3800
                        //nolint:errorlint
4✔
3801
                        if e, ok := pldErr.(hop.ErrInvalidPayload); ok {
4✔
3802
                                failedType = uint64(e.Type)
×
3803
                        }
×
3804

3805
                        // If we couldn't parse the payload, make our best
3806
                        // effort at creating an error encrypter that knows
3807
                        // what blinding type we were, but if we couldn't
3808
                        // parse the payload we have no way of knowing whether
3809
                        // we were the introduction node or not.
3810
                        //
3811
                        //nolint:ll
3812
                        obfuscator, failCode := chanIterator.ExtractErrorEncrypter(
4✔
3813
                                l.cfg.ExtractErrorEncrypter,
4✔
3814
                                // We need our route role here because we
4✔
3815
                                // couldn't parse or validate the payload.
4✔
3816
                                routeRole == hop.RouteRoleIntroduction,
4✔
3817
                        )
4✔
3818
                        if failCode != lnwire.CodeNone {
4✔
3819
                                l.log.Errorf("could not extract error "+
×
3820
                                        "encrypter: %v", pldErr)
×
3821

×
3822
                                // We can't process this htlc, send back
×
3823
                                // malformed.
×
3824
                                l.sendMalformedHTLCError(
×
3825
                                        add.ID, failureCode, add.OnionBlob,
×
3826
                                        &sourceRef,
×
3827
                                )
×
3828

×
3829
                                continue
×
3830
                        }
3831

3832
                        // TODO: currently none of the test unit infrastructure
3833
                        // is setup to handle TLV payloads, so testing this
3834
                        // would require implementing a separate mock iterator
3835
                        // for TLV payloads that also supports injecting invalid
3836
                        // payloads. Deferring this non-trival effort till a
3837
                        // later date
3838
                        failure := lnwire.NewInvalidOnionPayload(failedType, 0)
4✔
3839

4✔
3840
                        l.sendHTLCError(
4✔
3841
                                add, sourceRef, NewLinkError(failure),
4✔
3842
                                obfuscator, false,
4✔
3843
                        )
4✔
3844

4✔
3845
                        l.log.Errorf("unable to decode forwarding "+
4✔
3846
                                "instructions: %v", pldErr)
4✔
3847

4✔
3848
                        continue
4✔
3849
                }
3850

3851
                // Retrieve onion obfuscator from onion blob in order to
3852
                // produce initial obfuscation of the onion failureCode.
3853
                obfuscator, failureCode := chanIterator.ExtractErrorEncrypter(
4✔
3854
                        l.cfg.ExtractErrorEncrypter,
4✔
3855
                        routeRole == hop.RouteRoleIntroduction,
4✔
3856
                )
4✔
3857
                if failureCode != lnwire.CodeNone {
4✔
3858
                        // If we're unable to process the onion blob than we
×
3859
                        // should send the malformed htlc error to payment
×
3860
                        // sender.
×
3861
                        l.sendMalformedHTLCError(
×
3862
                                add.ID, failureCode, add.OnionBlob,
×
3863
                                &sourceRef,
×
3864
                        )
×
3865

×
3866
                        l.log.Errorf("unable to decode onion "+
×
3867
                                "obfuscator: %v", failureCode)
×
3868

×
3869
                        continue
×
3870
                }
3871

3872
                fwdInfo := pld.ForwardingInfo()
4✔
3873

4✔
3874
                // Check whether the payload we've just processed uses our
4✔
3875
                // node as the introduction point (gave us a blinding key in
4✔
3876
                // the payload itself) and fail it back if we don't support
4✔
3877
                // route blinding.
4✔
3878
                if fwdInfo.NextBlinding.IsSome() &&
4✔
3879
                        l.cfg.DisallowRouteBlinding {
8✔
3880

4✔
3881
                        failure := lnwire.NewInvalidBlinding(
4✔
3882
                                fn.Some(add.OnionBlob),
4✔
3883
                        )
4✔
3884

4✔
3885
                        l.sendHTLCError(
4✔
3886
                                add, sourceRef, NewLinkError(failure),
4✔
3887
                                obfuscator, false,
4✔
3888
                        )
4✔
3889

4✔
3890
                        l.log.Error("rejected htlc that uses use as an " +
4✔
3891
                                "introduction point when we do not support " +
4✔
3892
                                "route blinding")
4✔
3893

4✔
3894
                        continue
4✔
3895
                }
3896

3897
                switch fwdInfo.NextHop {
4✔
3898
                case hop.Exit:
4✔
3899
                        err := l.processExitHop(
4✔
3900
                                add, sourceRef, obfuscator, fwdInfo,
4✔
3901
                                heightNow, pld,
4✔
3902
                        )
4✔
3903
                        if err != nil {
8✔
3904
                                l.failf(LinkFailureError{
4✔
3905
                                        code: ErrInternalError,
4✔
3906
                                }, err.Error()) //nolint
4✔
3907

4✔
3908
                                return
4✔
3909
                        }
4✔
3910

3911
                // There are additional channels left within this route. So
3912
                // we'll simply do some forwarding package book-keeping.
3913
                default:
4✔
3914
                        // If hodl.AddIncoming is requested, we will not
4✔
3915
                        // validate the forwarded ADD, nor will we send the
4✔
3916
                        // packet to the htlc switch.
4✔
3917
                        if l.cfg.HodlMask.Active(hodl.AddIncoming) {
4✔
3918
                                l.log.Warnf(hodl.AddIncoming.Warning())
×
3919
                                continue
×
3920
                        }
3921

3922
                        endorseValue := l.experimentalEndorsement(
4✔
3923
                                record.CustomSet(add.CustomRecords),
4✔
3924
                        )
4✔
3925
                        endorseType := uint64(
4✔
3926
                                lnwire.ExperimentalEndorsementType,
4✔
3927
                        )
4✔
3928

4✔
3929
                        switch fwdPkg.State {
4✔
3930
                        case channeldb.FwdStateProcessed:
4✔
3931
                                // This add was not forwarded on the previous
4✔
3932
                                // processing phase, run it through our
4✔
3933
                                // validation pipeline to reproduce an error.
4✔
3934
                                // This may trigger a different error due to
4✔
3935
                                // expiring timelocks, but we expect that an
4✔
3936
                                // error will be reproduced.
4✔
3937
                                if !fwdPkg.FwdFilter.Contains(idx) {
4✔
3938
                                        break
×
3939
                                }
3940

3941
                                // Otherwise, it was already processed, we can
3942
                                // can collect it and continue.
3943
                                outgoingAdd := &lnwire.UpdateAddHTLC{
4✔
3944
                                        Expiry:        fwdInfo.OutgoingCTLV,
4✔
3945
                                        Amount:        fwdInfo.AmountToForward,
4✔
3946
                                        PaymentHash:   add.PaymentHash,
4✔
3947
                                        BlindingPoint: fwdInfo.NextBlinding,
4✔
3948
                                }
4✔
3949

4✔
3950
                                endorseValue.WhenSome(func(e byte) {
8✔
3951
                                        custRecords := map[uint64][]byte{
4✔
3952
                                                endorseType: {e},
4✔
3953
                                        }
4✔
3954

4✔
3955
                                        outgoingAdd.CustomRecords = custRecords
4✔
3956
                                })
4✔
3957

3958
                                // Finally, we'll encode the onion packet for
3959
                                // the _next_ hop using the hop iterator
3960
                                // decoded for the current hop.
3961
                                buf := bytes.NewBuffer(
4✔
3962
                                        outgoingAdd.OnionBlob[0:0],
4✔
3963
                                )
4✔
3964

4✔
3965
                                // We know this cannot fail, as this ADD
4✔
3966
                                // was marked forwarded in a previous
4✔
3967
                                // round of processing.
4✔
3968
                                chanIterator.EncodeNextHop(buf)
4✔
3969

4✔
3970
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
4✔
3971

4✔
3972
                                //nolint:ll
4✔
3973
                                updatePacket := &htlcPacket{
4✔
3974
                                        incomingChanID:       l.ShortChanID(),
4✔
3975
                                        incomingHTLCID:       add.ID,
4✔
3976
                                        outgoingChanID:       fwdInfo.NextHop,
4✔
3977
                                        sourceRef:            &sourceRef,
4✔
3978
                                        incomingAmount:       add.Amount,
4✔
3979
                                        amount:               outgoingAdd.Amount,
4✔
3980
                                        htlc:                 outgoingAdd,
4✔
3981
                                        obfuscator:           obfuscator,
4✔
3982
                                        incomingTimeout:      add.Expiry,
4✔
3983
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
4✔
3984
                                        inOnionCustomRecords: pld.CustomRecords(),
4✔
3985
                                        inboundFee:           inboundFee,
4✔
3986
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
4✔
3987
                                }
4✔
3988
                                switchPackets = append(
4✔
3989
                                        switchPackets, updatePacket,
4✔
3990
                                )
4✔
3991

4✔
3992
                                continue
4✔
3993
                        }
3994

3995
                        // TODO(roasbeef): ensure don't accept outrageous
3996
                        // timeout for htlc
3997

3998
                        // With all our forwarding constraints met, we'll
3999
                        // create the outgoing HTLC using the parameters as
4000
                        // specified in the forwarding info.
4001
                        addMsg := &lnwire.UpdateAddHTLC{
4✔
4002
                                Expiry:        fwdInfo.OutgoingCTLV,
4✔
4003
                                Amount:        fwdInfo.AmountToForward,
4✔
4004
                                PaymentHash:   add.PaymentHash,
4✔
4005
                                BlindingPoint: fwdInfo.NextBlinding,
4✔
4006
                        }
4✔
4007

4✔
4008
                        endorseValue.WhenSome(func(e byte) {
8✔
4009
                                addMsg.CustomRecords = map[uint64][]byte{
4✔
4010
                                        endorseType: {e},
4✔
4011
                                }
4✔
4012
                        })
4✔
4013

4014
                        // Finally, we'll encode the onion packet for the
4015
                        // _next_ hop using the hop iterator decoded for the
4016
                        // current hop.
4017
                        buf := bytes.NewBuffer(addMsg.OnionBlob[0:0])
4✔
4018
                        err := chanIterator.EncodeNextHop(buf)
4✔
4019
                        if err != nil {
4✔
4020
                                l.log.Errorf("unable to encode the "+
×
4021
                                        "remaining route %v", err)
×
4022

×
4023
                                cb := func(upd *lnwire.ChannelUpdate1) lnwire.FailureMessage { //nolint:ll
×
4024
                                        return lnwire.NewTemporaryChannelFailure(upd)
×
4025
                                }
×
4026

4027
                                failure := l.createFailureWithUpdate(
×
4028
                                        true, hop.Source, cb,
×
4029
                                )
×
4030

×
4031
                                l.sendHTLCError(
×
4032
                                        add, sourceRef, NewLinkError(failure),
×
4033
                                        obfuscator, false,
×
4034
                                )
×
4035
                                continue
×
4036
                        }
4037

4038
                        // Now that this add has been reprocessed, only append
4039
                        // it to our list of packets to forward to the switch
4040
                        // this is the first time processing the add. If the
4041
                        // fwd pkg has already been processed, then we entered
4042
                        // the above section to recreate a previous error.  If
4043
                        // the packet had previously been forwarded, it would
4044
                        // have been added to switchPackets at the top of this
4045
                        // section.
4046
                        if fwdPkg.State == channeldb.FwdStateLockedIn {
8✔
4047
                                inboundFee := l.cfg.FwrdingPolicy.InboundFee
4✔
4048

4✔
4049
                                //nolint:ll
4✔
4050
                                updatePacket := &htlcPacket{
4✔
4051
                                        incomingChanID:       l.ShortChanID(),
4✔
4052
                                        incomingHTLCID:       add.ID,
4✔
4053
                                        outgoingChanID:       fwdInfo.NextHop,
4✔
4054
                                        sourceRef:            &sourceRef,
4✔
4055
                                        incomingAmount:       add.Amount,
4✔
4056
                                        amount:               addMsg.Amount,
4✔
4057
                                        htlc:                 addMsg,
4✔
4058
                                        obfuscator:           obfuscator,
4✔
4059
                                        incomingTimeout:      add.Expiry,
4✔
4060
                                        outgoingTimeout:      fwdInfo.OutgoingCTLV,
4✔
4061
                                        inOnionCustomRecords: pld.CustomRecords(),
4✔
4062
                                        inboundFee:           inboundFee,
4✔
4063
                                        inWireCustomRecords:  add.CustomRecords.Copy(),
4✔
4064
                                }
4✔
4065

4✔
4066
                                fwdPkg.FwdFilter.Set(idx)
4✔
4067
                                switchPackets = append(switchPackets,
4✔
4068
                                        updatePacket)
4✔
4069
                        }
4✔
4070
                }
4071
        }
4072

4073
        // Commit the htlcs we are intending to forward if this package has not
4074
        // been fully processed.
4075
        if fwdPkg.State == channeldb.FwdStateLockedIn {
8✔
4076
                err := l.channel.SetFwdFilter(fwdPkg.Height, fwdPkg.FwdFilter)
4✔
4077
                if err != nil {
4✔
4078
                        l.failf(LinkFailureError{code: ErrInternalError},
×
4079
                                "unable to set fwd filter: %v", err)
×
4080
                        return
×
4081
                }
×
4082
        }
4083

4084
        if len(switchPackets) == 0 {
8✔
4085
                return
4✔
4086
        }
4✔
4087

4088
        replay := fwdPkg.State != channeldb.FwdStateLockedIn
4✔
4089

4✔
4090
        l.log.Debugf("forwarding %d packets to switch: replay=%v",
4✔
4091
                len(switchPackets), replay)
4✔
4092

4✔
4093
        // NOTE: This call is made synchronous so that we ensure all circuits
4✔
4094
        // are committed in the exact order that they are processed in the link.
4✔
4095
        // Failing to do this could cause reorderings/gaps in the range of
4✔
4096
        // opened circuits, which violates assumptions made by the circuit
4✔
4097
        // trimming.
4✔
4098
        l.forwardBatch(replay, switchPackets...)
4✔
4099
}
4100

4101
// experimentalEndorsement returns the value to set for our outgoing
4102
// experimental endorsement field, and a boolean indicating whether it should
4103
// be populated on the outgoing htlc.
4104
func (l *channelLink) experimentalEndorsement(
4105
        customUpdateAdd record.CustomSet) fn.Option[byte] {
4✔
4106

4✔
4107
        // Only relay experimental signal if we are within the experiment
4✔
4108
        // period.
4✔
4109
        if !l.cfg.ShouldFwdExpEndorsement() {
8✔
4110
                return fn.None[byte]()
4✔
4111
        }
4✔
4112

4113
        // If we don't have any custom records or the experimental field is
4114
        // not set, just forward a zero value.
4115
        if len(customUpdateAdd) == 0 {
8✔
4116
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
4✔
4117
        }
4✔
4118

4119
        t := uint64(lnwire.ExperimentalEndorsementType)
4✔
4120
        value, set := customUpdateAdd[t]
4✔
4121
        if !set {
4✔
4122
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4123
        }
×
4124

4125
        // We expect at least one byte for this field, consider it invalid if
4126
        // it has no data and just forward a zero value.
4127
        if len(value) == 0 {
4✔
4128
                return fn.Some[byte](lnwire.ExperimentalUnendorsed)
×
4129
        }
×
4130

4131
        // Only forward endorsed if the incoming link is endorsed.
4132
        if value[0] == lnwire.ExperimentalEndorsed {
8✔
4133
                return fn.Some[byte](lnwire.ExperimentalEndorsed)
4✔
4134
        }
4✔
4135

4136
        // Forward as unendorsed otherwise, including cases where we've
4137
        // received an invalid value that uses more than 3 bits of information.
4138
        return fn.Some[byte](lnwire.ExperimentalUnendorsed)
4✔
4139
}
4140

4141
// processExitHop handles an htlc for which this link is the exit hop. It
4142
// returns a boolean indicating whether the commitment tx needs an update.
4143
func (l *channelLink) processExitHop(add lnwire.UpdateAddHTLC,
4144
        sourceRef channeldb.AddRef, obfuscator hop.ErrorEncrypter,
4145
        fwdInfo hop.ForwardingInfo, heightNow uint32,
4146
        payload invoices.Payload) error {
4✔
4147

4✔
4148
        // If hodl.ExitSettle is requested, we will not validate the final hop's
4✔
4149
        // ADD, nor will we settle the corresponding invoice or respond with the
4✔
4150
        // preimage.
4✔
4151
        if l.cfg.HodlMask.Active(hodl.ExitSettle) {
8✔
4152
                l.log.Warnf("%s for htlc(rhash=%x,htlcIndex=%v)",
4✔
4153
                        hodl.ExitSettle.Warning(), add.PaymentHash, add.ID)
4✔
4154

4✔
4155
                return nil
4✔
4156
        }
4✔
4157

4158
        // As we're the exit hop, we'll double check the hop-payload included in
4159
        // the HTLC to ensure that it was crafted correctly by the sender and
4160
        // is compatible with the HTLC we were extended.
4161
        //
4162
        // For a special case, if the fwdInfo doesn't have any blinded path
4163
        // information, and the incoming HTLC had special extra data, then
4164
        // we'll skip this amount check. The invoice acceptor will make sure we
4165
        // reject the HTLC if it's not containing the correct amount after
4166
        // examining the custom data.
4167
        hasBlindedPath := fwdInfo.NextBlinding.IsSome()
4✔
4168
        customHTLC := len(add.CustomRecords) > 0 && !hasBlindedPath
4✔
4169
        log.Tracef("Exit hop has_blinded_path=%v custom_htlc_bypass=%v",
4✔
4170
                hasBlindedPath, customHTLC)
4✔
4171

4✔
4172
        if !customHTLC && add.Amount < fwdInfo.AmountToForward {
4✔
4173
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
×
4174
                        "incompatible value: expected <=%v, got %v",
×
4175
                        add.PaymentHash, add.Amount, fwdInfo.AmountToForward)
×
4176

×
4177
                failure := NewLinkError(
×
4178
                        lnwire.NewFinalIncorrectHtlcAmount(add.Amount),
×
4179
                )
×
4180
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
×
4181

×
4182
                return nil
×
4183
        }
×
4184

4185
        // We'll also ensure that our time-lock value has been computed
4186
        // correctly.
4187
        if add.Expiry < fwdInfo.OutgoingCTLV {
4✔
4188
                l.log.Errorf("onion payload of incoming htlc(%x) has "+
×
4189
                        "incompatible time-lock: expected <=%v, got %v",
×
4190
                        add.PaymentHash, add.Expiry, fwdInfo.OutgoingCTLV)
×
4191

×
4192
                failure := NewLinkError(
×
4193
                        lnwire.NewFinalIncorrectCltvExpiry(add.Expiry),
×
4194
                )
×
4195

×
4196
                l.sendHTLCError(add, sourceRef, failure, obfuscator, true)
×
4197

×
4198
                return nil
×
4199
        }
×
4200

4201
        // Notify the invoiceRegistry of the exit hop htlc. If we crash right
4202
        // after this, this code will be re-executed after restart. We will
4203
        // receive back a resolution event.
4204
        invoiceHash := lntypes.Hash(add.PaymentHash)
4✔
4205

4✔
4206
        circuitKey := models.CircuitKey{
4✔
4207
                ChanID: l.ShortChanID(),
4✔
4208
                HtlcID: add.ID,
4✔
4209
        }
4✔
4210

4✔
4211
        event, err := l.cfg.Registry.NotifyExitHopHtlc(
4✔
4212
                invoiceHash, add.Amount, add.Expiry, int32(heightNow),
4✔
4213
                circuitKey, l.hodlQueue.ChanIn(), add.CustomRecords, payload,
4✔
4214
        )
4✔
4215
        if err != nil {
8✔
4216
                return err
4✔
4217
        }
4✔
4218

4219
        // Create a hodlHtlc struct and decide either resolved now or later.
4220
        htlc := hodlHtlc{
4✔
4221
                add:        add,
4✔
4222
                sourceRef:  sourceRef,
4✔
4223
                obfuscator: obfuscator,
4✔
4224
        }
4✔
4225

4✔
4226
        // If the event is nil, the invoice is being held, so we save payment
4✔
4227
        // descriptor for future reference.
4✔
4228
        if event == nil {
8✔
4229
                l.hodlMap[circuitKey] = htlc
4✔
4230
                return nil
4✔
4231
        }
4✔
4232

4233
        // Process the received resolution.
4234
        return l.processHtlcResolution(event, htlc)
4✔
4235
}
4236

4237
// settleHTLC settles the HTLC on the channel.
4238
func (l *channelLink) settleHTLC(preimage lntypes.Preimage,
4239
        htlcIndex uint64, sourceRef channeldb.AddRef) error {
4✔
4240

4✔
4241
        hash := preimage.Hash()
4✔
4242

4✔
4243
        l.log.Infof("settling htlc %v as exit hop", hash)
4✔
4244

4✔
4245
        err := l.channel.SettleHTLC(
4✔
4246
                preimage, htlcIndex, &sourceRef, nil, nil,
4✔
4247
        )
4✔
4248
        if err != nil {
4✔
4249
                return fmt.Errorf("unable to settle htlc: %w", err)
×
4250
        }
×
4251

4252
        // If the link is in hodl.BogusSettle mode, replace the preimage with a
4253
        // fake one before sending it to the peer.
4254
        if l.cfg.HodlMask.Active(hodl.BogusSettle) {
8✔
4255
                l.log.Warnf(hodl.BogusSettle.Warning())
4✔
4256
                preimage = [32]byte{}
4✔
4257
                copy(preimage[:], bytes.Repeat([]byte{2}, 32))
4✔
4258
        }
4✔
4259

4260
        // HTLC was successfully settled locally send notification about it
4261
        // remote peer.
4262
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFulfillHTLC{
4✔
4263
                ChanID:          l.ChanID(),
4✔
4264
                ID:              htlcIndex,
4✔
4265
                PaymentPreimage: preimage,
4✔
4266
        })
4✔
4267

4✔
4268
        // Once we have successfully settled the htlc, notify a settle event.
4✔
4269
        l.cfg.HtlcNotifier.NotifySettleEvent(
4✔
4270
                HtlcKey{
4✔
4271
                        IncomingCircuit: models.CircuitKey{
4✔
4272
                                ChanID: l.ShortChanID(),
4✔
4273
                                HtlcID: htlcIndex,
4✔
4274
                        },
4✔
4275
                },
4✔
4276
                preimage,
4✔
4277
                HtlcEventTypeReceive,
4✔
4278
        )
4✔
4279

4✔
4280
        return nil
4✔
4281
}
4282

4283
// forwardBatch forwards the given htlcPackets to the switch, and waits on the
4284
// err chan for the individual responses. This method is intended to be spawned
4285
// as a goroutine so the responses can be handled in the background.
4286
func (l *channelLink) forwardBatch(replay bool, packets ...*htlcPacket) {
4✔
4287
        // Don't forward packets for which we already have a response in our
4✔
4288
        // mailbox. This could happen if a packet fails and is buffered in the
4✔
4289
        // mailbox, and the incoming link flaps.
4✔
4290
        var filteredPkts = make([]*htlcPacket, 0, len(packets))
4✔
4291
        for _, pkt := range packets {
8✔
4292
                if l.mailBox.HasPacket(pkt.inKey()) {
8✔
4293
                        continue
4✔
4294
                }
4295

4296
                filteredPkts = append(filteredPkts, pkt)
4✔
4297
        }
4298

4299
        err := l.cfg.ForwardPackets(l.cg.Done(), replay, filteredPkts...)
4✔
4300
        if err != nil {
4✔
4301
                log.Errorf("Unhandled error while reforwarding htlc "+
×
4302
                        "settle/fail over htlcswitch: %v", err)
×
4303
        }
×
4304
}
4305

4306
// sendHTLCError functions cancels HTLC and send cancel message back to the
4307
// peer from which HTLC was received.
4308
func (l *channelLink) sendHTLCError(add lnwire.UpdateAddHTLC,
4309
        sourceRef channeldb.AddRef, failure *LinkError,
4310
        e hop.ErrorEncrypter, isReceive bool) {
4✔
4311

4✔
4312
        reason, err := e.EncryptFirstHop(failure.WireMessage())
4✔
4313
        if err != nil {
4✔
4314
                l.log.Errorf("unable to obfuscate error: %v", err)
×
4315
                return
×
4316
        }
×
4317

4318
        err = l.channel.FailHTLC(add.ID, reason, &sourceRef, nil, nil)
4✔
4319
        if err != nil {
4✔
4320
                l.log.Errorf("unable cancel htlc: %v", err)
×
4321
                return
×
4322
        }
×
4323

4324
        // Send the appropriate failure message depending on whether we're
4325
        // in a blinded route or not.
4326
        if err := l.sendIncomingHTLCFailureMsg(
4✔
4327
                add.ID, e, reason,
4✔
4328
        ); err != nil {
4✔
4329
                l.log.Errorf("unable to send HTLC failure: %v", err)
×
4330
                return
×
4331
        }
×
4332

4333
        // Notify a link failure on our incoming link. Outgoing htlc information
4334
        // is not available at this point, because we have not decrypted the
4335
        // onion, so it is excluded.
4336
        var eventType HtlcEventType
4✔
4337
        if isReceive {
8✔
4338
                eventType = HtlcEventTypeReceive
4✔
4339
        } else {
8✔
4340
                eventType = HtlcEventTypeForward
4✔
4341
        }
4✔
4342

4343
        l.cfg.HtlcNotifier.NotifyLinkFailEvent(
4✔
4344
                HtlcKey{
4✔
4345
                        IncomingCircuit: models.CircuitKey{
4✔
4346
                                ChanID: l.ShortChanID(),
4✔
4347
                                HtlcID: add.ID,
4✔
4348
                        },
4✔
4349
                },
4✔
4350
                HtlcInfo{
4✔
4351
                        IncomingTimeLock: add.Expiry,
4✔
4352
                        IncomingAmt:      add.Amount,
4✔
4353
                },
4✔
4354
                eventType,
4✔
4355
                failure,
4✔
4356
                true,
4✔
4357
        )
4✔
4358
}
4359

4360
// sendPeerHTLCFailure handles sending a HTLC failure message back to the
4361
// peer from which the HTLC was received. This function is primarily used to
4362
// handle the special requirements of route blinding, specifically:
4363
// - Forwarding nodes must switch out any errors with MalformedFailHTLC
4364
// - Introduction nodes should return regular HTLC failure messages.
4365
//
4366
// It accepts the original opaque failure, which will be used in the case
4367
// that we're not part of a blinded route and an error encrypter that'll be
4368
// used if we are the introduction node and need to present an error as if
4369
// we're the failing party.
4370
func (l *channelLink) sendIncomingHTLCFailureMsg(htlcIndex uint64,
4371
        e hop.ErrorEncrypter,
4372
        originalFailure lnwire.OpaqueReason) error {
4✔
4373

4✔
4374
        var msg lnwire.Message
4✔
4375
        switch {
4✔
4376
        // Our circuit's error encrypter will be nil if this was a locally
4377
        // initiated payment. We can only hit a blinded error for a locally
4378
        // initiated payment if we allow ourselves to be picked as the
4379
        // introduction node for our own payments and in that case we
4380
        // shouldn't reach this code. To prevent the HTLC getting stuck,
4381
        // we fail it back and log an error.
4382
        // code.
4383
        case e == nil:
×
4384
                msg = &lnwire.UpdateFailHTLC{
×
4385
                        ChanID: l.ChanID(),
×
4386
                        ID:     htlcIndex,
×
4387
                        Reason: originalFailure,
×
4388
                }
×
4389

×
4390
                l.log.Errorf("Unexpected blinded failure when "+
×
4391
                        "we are the sending node, incoming htlc: %v(%v)",
×
4392
                        l.ShortChanID(), htlcIndex)
×
4393

4394
        // For cleartext hops (ie, non-blinded/normal) we don't need any
4395
        // transformation on the error message and can just send the original.
4396
        case !e.Type().IsBlinded():
4✔
4397
                msg = &lnwire.UpdateFailHTLC{
4✔
4398
                        ChanID: l.ChanID(),
4✔
4399
                        ID:     htlcIndex,
4✔
4400
                        Reason: originalFailure,
4✔
4401
                }
4✔
4402

4403
        // When we're the introduction node, we need to convert the error to
4404
        // a UpdateFailHTLC.
4405
        case e.Type() == hop.EncrypterTypeIntroduction:
4✔
4406
                l.log.Debugf("Introduction blinded node switching out failure "+
4✔
4407
                        "error: %v", htlcIndex)
4✔
4408

4✔
4409
                // The specification does not require that we set the onion
4✔
4410
                // blob.
4✔
4411
                failureMsg := lnwire.NewInvalidBlinding(
4✔
4412
                        fn.None[[lnwire.OnionPacketSize]byte](),
4✔
4413
                )
4✔
4414
                reason, err := e.EncryptFirstHop(failureMsg)
4✔
4415
                if err != nil {
4✔
4416
                        return err
×
4417
                }
×
4418

4419
                msg = &lnwire.UpdateFailHTLC{
4✔
4420
                        ChanID: l.ChanID(),
4✔
4421
                        ID:     htlcIndex,
4✔
4422
                        Reason: reason,
4✔
4423
                }
4✔
4424

4425
        // If we are a relaying node, we need to switch out any error that
4426
        // we've received to a malformed HTLC error.
4427
        case e.Type() == hop.EncrypterTypeRelaying:
4✔
4428
                l.log.Debugf("Relaying blinded node switching out malformed "+
4✔
4429
                        "error: %v", htlcIndex)
4✔
4430

4✔
4431
                msg = &lnwire.UpdateFailMalformedHTLC{
4✔
4432
                        ChanID:      l.ChanID(),
4✔
4433
                        ID:          htlcIndex,
4✔
4434
                        FailureCode: lnwire.CodeInvalidBlinding,
4✔
4435
                }
4✔
4436

4437
        default:
×
4438
                return fmt.Errorf("unexpected encrypter: %d", e)
×
4439
        }
4440

4441
        if err := l.cfg.Peer.SendMessage(false, msg); err != nil {
4✔
4442
                l.log.Warnf("Send update fail failed: %v", err)
×
4443
        }
×
4444

4445
        return nil
4✔
4446
}
4447

4448
// sendMalformedHTLCError helper function which sends the malformed HTLC update
4449
// to the payment sender.
4450
func (l *channelLink) sendMalformedHTLCError(htlcIndex uint64,
4451
        code lnwire.FailCode, onionBlob [lnwire.OnionPacketSize]byte,
4452
        sourceRef *channeldb.AddRef) {
4✔
4453

4✔
4454
        shaOnionBlob := sha256.Sum256(onionBlob[:])
4✔
4455
        err := l.channel.MalformedFailHTLC(htlcIndex, code, shaOnionBlob, sourceRef)
4✔
4456
        if err != nil {
4✔
4457
                l.log.Errorf("unable cancel htlc: %v", err)
×
4458
                return
×
4459
        }
×
4460

4461
        l.cfg.Peer.SendMessage(false, &lnwire.UpdateFailMalformedHTLC{
4✔
4462
                ChanID:       l.ChanID(),
4✔
4463
                ID:           htlcIndex,
4✔
4464
                ShaOnionBlob: shaOnionBlob,
4✔
4465
                FailureCode:  code,
4✔
4466
        })
4✔
4467
}
4468

4469
// failf is a function which is used to encapsulate the action necessary for
4470
// properly failing the link. It takes a LinkFailureError, which will be passed
4471
// to the OnChannelFailure closure, in order for it to determine if we should
4472
// force close the channel, and if we should send an error message to the
4473
// remote peer.
4474
func (l *channelLink) failf(linkErr LinkFailureError, format string,
4475
        a ...interface{}) {
4✔
4476

4✔
4477
        reason := fmt.Errorf(format, a...)
4✔
4478

4✔
4479
        // Return if we have already notified about a failure.
4✔
4480
        if l.failed {
8✔
4481
                l.log.Warnf("ignoring link failure (%v), as link already "+
4✔
4482
                        "failed", reason)
4✔
4483
                return
4✔
4484
        }
4✔
4485

4486
        l.log.Errorf("failing link: %s with error: %v", reason, linkErr)
4✔
4487

4✔
4488
        // Set failed, such that we won't process any more updates, and notify
4✔
4489
        // the peer about the failure.
4✔
4490
        l.failed = true
4✔
4491
        l.cfg.OnChannelFailure(l.ChanID(), l.ShortChanID(), linkErr)
4✔
4492
}
4493

4494
// FundingCustomBlob returns the custom funding blob of the channel that this
4495
// link is associated with. The funding blob represents static information about
4496
// the channel that was created at channel funding time.
4497
func (l *channelLink) FundingCustomBlob() fn.Option[tlv.Blob] {
×
4498
        if l.channel == nil {
×
4499
                return fn.None[tlv.Blob]()
×
4500
        }
×
4501

4502
        if l.channel.State() == nil {
×
4503
                return fn.None[tlv.Blob]()
×
4504
        }
×
4505

4506
        return l.channel.State().CustomBlob
×
4507
}
4508

4509
// CommitmentCustomBlob returns the custom blob of the current local commitment
4510
// of the channel that this link is associated with.
4511
func (l *channelLink) CommitmentCustomBlob() fn.Option[tlv.Blob] {
×
4512
        if l.channel == nil {
×
4513
                return fn.None[tlv.Blob]()
×
4514
        }
×
4515

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