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

lightningnetwork / lnd / 17777197509

16 Sep 2025 07:46PM UTC coverage: 57.202% (-9.5%) from 66.657%
17777197509

Pull #9489

github

web-flow
Merge bd2ae0bae into cbed86e21
Pull Request #9489: multi: add BuildOnion, SendOnion, and TrackOnion RPCs

329 of 564 new or added lines in 12 files covered. (58.33%)

28576 existing lines in 457 files now uncovered.

99724 of 174338 relevant lines covered (57.2%)

1.78 hits per line

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

75.03
/htlcswitch/switch.go
1
package htlcswitch
2

3
import (
4
        "bytes"
5
        "context"
6
        "errors"
7
        "fmt"
8
        "math/rand"
9
        "sync"
10
        "sync/atomic"
11
        "time"
12

13
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
14
        "github.com/btcsuite/btcd/btcutil"
15
        "github.com/btcsuite/btcd/wire"
16
        "github.com/lightningnetwork/lnd/chainntnfs"
17
        "github.com/lightningnetwork/lnd/channeldb"
18
        "github.com/lightningnetwork/lnd/clock"
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/hop"
23
        "github.com/lightningnetwork/lnd/kvdb"
24
        "github.com/lightningnetwork/lnd/lntypes"
25
        "github.com/lightningnetwork/lnd/lnutils"
26
        "github.com/lightningnetwork/lnd/lnwallet"
27
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
28
        "github.com/lightningnetwork/lnd/lnwire"
29
        "github.com/lightningnetwork/lnd/ticker"
30
)
31

32
const (
33
        // DefaultFwdEventInterval is the duration between attempts to flush
34
        // pending forwarding events to disk.
35
        DefaultFwdEventInterval = 15 * time.Second
36

37
        // DefaultLogInterval is the duration between attempts to log statistics
38
        // about forwarding events.
39
        DefaultLogInterval = 10 * time.Second
40

41
        // DefaultAckInterval is the duration between attempts to ack any settle
42
        // fails in a forwarding package.
43
        DefaultAckInterval = 15 * time.Second
44

45
        // DefaultMailboxDeliveryTimeout is the duration after which Adds will
46
        // be cancelled if they could not get added to an outgoing commitment.
47
        DefaultMailboxDeliveryTimeout = time.Minute
48
)
49

50
var (
51
        // ErrChannelLinkNotFound is used when channel link hasn't been found.
52
        ErrChannelLinkNotFound = errors.New("channel link not found")
53

54
        // ErrDuplicateAdd signals that the ADD htlc was already forwarded
55
        // through the switch and is locked into another commitment txn.
56
        ErrDuplicateAdd = errors.New("duplicate add HTLC detected")
57

58
        // ErrUnknownErrorDecryptor signals that we were unable to locate the
59
        // error decryptor for this payment. This is likely due to restarting
60
        // the daemon.
61
        ErrUnknownErrorDecryptor = errors.New("unknown error decryptor")
62

63
        // ErrSwitchExiting signaled when the switch has received a shutdown
64
        // request.
65
        ErrSwitchExiting = errors.New("htlcswitch shutting down")
66

67
        // ErrNoLinksFound is an error returned when we attempt to retrieve the
68
        // active links in the switch for a specific destination.
69
        ErrNoLinksFound = errors.New("no channel links found")
70

71
        // ErrUnreadableFailureMessage is returned when the failure message
72
        // cannot be decrypted.
73
        ErrUnreadableFailureMessage = errors.New("unreadable failure message")
74

75
        // ErrLocalAddFailed signals that the ADD htlc for a local payment
76
        // failed to be processed.
77
        ErrLocalAddFailed = errors.New("local add HTLC failed")
78

79
        // errFeeExposureExceeded is only surfaced to callers of SendHTLC and
80
        // signals that sending the HTLC would exceed the outgoing link's fee
81
        // exposure threshold.
82
        errFeeExposureExceeded = errors.New("fee exposure exceeded")
83

84
        // DefaultMaxFeeExposure is the default threshold after which we'll
85
        // fail payments if they increase our fee exposure. This is currently
86
        // set to 500m msats.
87
        DefaultMaxFeeExposure = lnwire.MilliSatoshi(500_000_000)
88
)
89

90
// plexPacket encapsulates switch packet and adds error channel to receive
91
// error from request handler.
92
type plexPacket struct {
93
        pkt *htlcPacket
94
        err chan error
95
}
96

97
// ChanClose represents a request which close a particular channel specified by
98
// its id.
99
type ChanClose struct {
100
        // CloseType is a variable which signals the type of channel closure the
101
        // peer should execute.
102
        CloseType contractcourt.ChannelCloseType
103

104
        // ChanPoint represent the id of the channel which should be closed.
105
        ChanPoint *wire.OutPoint
106

107
        // TargetFeePerKw is the ideal fee that was specified by the caller.
108
        // This value is only utilized if the closure type is CloseRegular.
109
        // This will be the starting offered fee when the fee negotiation
110
        // process for the cooperative closure transaction kicks off.
111
        TargetFeePerKw chainfee.SatPerKWeight
112

113
        // MaxFee is the highest fee the caller is willing to pay.
114
        //
115
        // NOTE: This field is only respected if the caller is the initiator of
116
        // the channel.
117
        MaxFee chainfee.SatPerKWeight
118

119
        // DeliveryScript is an optional delivery script to pay funds out to.
120
        DeliveryScript lnwire.DeliveryAddress
121

122
        // Updates is used by request creator to receive the notifications about
123
        // execution of the close channel request.
124
        Updates chan interface{}
125

126
        // Err is used by request creator to receive request execution error.
127
        Err chan error
128

129
        // Ctx is a context linked to the lifetime of the caller.
130
        Ctx context.Context //nolint:containedctx
131
}
132

133
// Config defines the configuration for the service. ALL elements within the
134
// configuration MUST be non-nil for the service to carry out its duties.
135
type Config struct {
136
        // FwdingLog is an interface that will be used by the switch to log
137
        // forwarding events. A forwarding event happens each time a payment
138
        // circuit is successfully completed. So when we forward an HTLC, and a
139
        // settle is eventually received.
140
        FwdingLog ForwardingLog
141

142
        // LocalChannelClose kicks-off the workflow to execute a cooperative or
143
        // forced unilateral closure of the channel initiated by a local
144
        // subsystem.
145
        LocalChannelClose func(pubKey []byte, request *ChanClose)
146

147
        // DB is the database backend that will be used to back the switch's
148
        // persistent circuit map.
149
        DB kvdb.Backend
150

151
        // FetchAllOpenChannels is a function that fetches all currently open
152
        // channels from the channel database.
153
        FetchAllOpenChannels func() ([]*channeldb.OpenChannel, error)
154

155
        // FetchAllChannels is a function that fetches all pending open, open,
156
        // and waiting close channels from the database.
157
        FetchAllChannels func() ([]*channeldb.OpenChannel, error)
158

159
        // FetchClosedChannels is a function that fetches all closed channels
160
        // from the channel database.
161
        FetchClosedChannels func(
162
                pendingOnly bool) ([]*channeldb.ChannelCloseSummary, error)
163

164
        // SwitchPackager provides access to the forwarding packages of all
165
        // active channels. This gives the switch the ability to read arbitrary
166
        // forwarding packages, and ack settles and fails contained within them.
167
        SwitchPackager channeldb.FwdOperator
168

169
        // ExtractErrorEncrypter is an interface allowing switch to reextract
170
        // error encrypters stored in the circuit map on restarts, since they
171
        // are not stored directly within the database.
172
        ExtractErrorEncrypter hop.ErrorEncrypterExtracter
173

174
        // FetchLastChannelUpdate retrieves the latest routing policy for a
175
        // target channel. This channel will typically be the outgoing channel
176
        // specified when we receive an incoming HTLC.  This will be used to
177
        // provide payment senders our latest policy when sending encrypted
178
        // error messages.
179
        FetchLastChannelUpdate func(lnwire.ShortChannelID) (
180
                *lnwire.ChannelUpdate1, error)
181

182
        // Notifier is an instance of a chain notifier that we'll use to signal
183
        // the switch when a new block has arrived.
184
        Notifier chainntnfs.ChainNotifier
185

186
        // HtlcNotifier is an instance of a htlcNotifier which we will pipe htlc
187
        // events through.
188
        HtlcNotifier htlcNotifier
189

190
        // FwdEventTicker is a signal that instructs the htlcswitch to flush any
191
        // pending forwarding events.
192
        FwdEventTicker ticker.Ticker
193

194
        // LogEventTicker is a signal instructing the htlcswitch to log
195
        // aggregate stats about it's forwarding during the last interval.
196
        LogEventTicker ticker.Ticker
197

198
        // AckEventTicker is a signal instructing the htlcswitch to ack any settle
199
        // fails in forwarding packages.
200
        AckEventTicker ticker.Ticker
201

202
        // AllowCircularRoute is true if the user has configured their node to
203
        // allow forwards that arrive and depart our node over the same channel.
204
        AllowCircularRoute bool
205

206
        // RejectHTLC is a flag that instructs the htlcswitch to reject any
207
        // HTLCs that are not from the source hop.
208
        RejectHTLC bool
209

210
        // Clock is a time source for the switch.
211
        Clock clock.Clock
212

213
        // MailboxDeliveryTimeout is the interval after which Adds will be
214
        // cancelled if they have not been yet been delivered to a link. The
215
        // computed deadline will expiry this long after the Adds are added to
216
        // a mailbox via AddPacket.
217
        MailboxDeliveryTimeout time.Duration
218

219
        // MaxFeeExposure is the threshold in milli-satoshis after which we'll
220
        // fail incoming or outgoing payments for a particular channel.
221
        MaxFeeExposure lnwire.MilliSatoshi
222

223
        // SignAliasUpdate is used when sending FailureMessages backwards for
224
        // option_scid_alias channels. This avoids a potential privacy leak by
225
        // replacing the public, confirmed SCID with the alias in the
226
        // ChannelUpdate.
227
        SignAliasUpdate func(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
228
                error)
229

230
        // IsAlias returns whether or not a given SCID is an alias.
231
        IsAlias func(scid lnwire.ShortChannelID) bool
232
}
233

234
// Switch is the central messaging bus for all incoming/outgoing HTLCs.
235
// Connected peers with active channels are treated as named interfaces which
236
// refer to active channels as links. A link is the switch's message
237
// communication point with the goroutine that manages an active channel. New
238
// links are registered each time a channel is created, and unregistered once
239
// the channel is closed. The switch manages the hand-off process for multi-hop
240
// HTLCs, forwarding HTLCs initiated from within the daemon, and finally
241
// notifies users local-systems concerning their outstanding payment requests.
242
type Switch struct {
243
        started  int32 // To be used atomically.
244
        shutdown int32 // To be used atomically.
245

246
        // bestHeight is the best known height of the main chain. The links will
247
        // be used this information to govern decisions based on HTLC timeouts.
248
        // This will be retrieved by the registered links atomically.
249
        bestHeight uint32
250

251
        wg   sync.WaitGroup
252
        quit chan struct{}
253

254
        // cfg is a copy of the configuration struct that the htlc switch
255
        // service was initialized with.
256
        cfg *Config
257

258
        // networkResults stores the results of payments initiated by the user.
259
        // The store is used to later look up the payments and notify the
260
        // user of the result when they are complete. Each payment attempt
261
        // should be given a unique integer ID when it is created, otherwise
262
        // results might be overwritten.
263
        networkResults *networkResultStore
264

265
        // circuits is storage for payment circuits which are used to
266
        // forward the settle/fail htlc updates back to the add htlc initiator.
267
        circuits CircuitMap
268

269
        // mailOrchestrator manages the lifecycle of mailboxes used throughout
270
        // the switch, and facilitates delayed delivery of packets to links that
271
        // later come online.
272
        mailOrchestrator *mailOrchestrator
273

274
        // indexMtx is a read/write mutex that protects the set of indexes
275
        // below.
276
        indexMtx sync.RWMutex
277

278
        // pendingLinkIndex holds links that have not had their final, live
279
        // short_chan_id assigned.
280
        pendingLinkIndex map[lnwire.ChannelID]ChannelLink
281

282
        // links is a map of channel id and channel link which manages
283
        // this channel.
284
        linkIndex map[lnwire.ChannelID]ChannelLink
285

286
        // forwardingIndex is an index which is consulted by the switch when it
287
        // needs to locate the next hop to forward an incoming/outgoing HTLC
288
        // update to/from.
289
        //
290
        // TODO(roasbeef): eventually add a NetworkHop mapping before the
291
        // ChannelLink
292
        forwardingIndex map[lnwire.ShortChannelID]ChannelLink
293

294
        // interfaceIndex maps the compressed public key of a peer to all the
295
        // channels that the switch maintains with that peer.
296
        interfaceIndex map[[33]byte]map[lnwire.ChannelID]ChannelLink
297

298
        // linkStopIndex stores the currently stopping ChannelLinks,
299
        // represented by their ChannelID. The key is the link's ChannelID and
300
        // the value is a chan that is closed when the link has fully stopped.
301
        // This map is only added to if RemoveLink is called and is not added
302
        // to when the Switch is shutting down and calls Stop() on each link.
303
        //
304
        // MUST be used with the indexMtx.
305
        linkStopIndex map[lnwire.ChannelID]chan struct{}
306

307
        // htlcPlex is the channel which all connected links use to coordinate
308
        // the setup/teardown of Sphinx (onion routing) payment circuits.
309
        // Active links forward any add/settle messages over this channel each
310
        // state transition, sending new adds/settles which are fully locked
311
        // in.
312
        htlcPlex chan *plexPacket
313

314
        // chanCloseRequests is used to transfer the channel close request to
315
        // the channel close handler.
316
        chanCloseRequests chan *ChanClose
317

318
        // resolutionMsgs is the channel that all external contract resolution
319
        // messages will be sent over.
320
        resolutionMsgs chan *resolutionMsg
321

322
        // pendingFwdingEvents is the set of forwarding events which have been
323
        // collected during the current interval, but hasn't yet been written
324
        // to the forwarding log.
325
        fwdEventMtx         sync.Mutex
326
        pendingFwdingEvents []channeldb.ForwardingEvent
327

328
        // blockEpochStream is an active block epoch event stream backed by an
329
        // active ChainNotifier instance. This will be used to retrieve the
330
        // latest height of the chain.
331
        blockEpochStream *chainntnfs.BlockEpochEvent
332

333
        // pendingSettleFails is the set of settle/fail entries that we need to
334
        // ack in the forwarding package of the outgoing link. This was added to
335
        // make pipelining settles more efficient.
336
        pendingSettleFails []channeldb.SettleFailRef
337

338
        // resMsgStore is used to store the set of ResolutionMsg that come from
339
        // contractcourt. This is used so the Switch can properly forward them,
340
        // even on restarts.
341
        resMsgStore *resolutionStore
342

343
        // aliasToReal is a map used for option-scid-alias feature-bit links.
344
        // The alias SCID is the key and the real, confirmed SCID is the value.
345
        // If the channel is unconfirmed, there will not be a mapping for it.
346
        // Since channels can have multiple aliases, this map is essentially a
347
        // N->1 mapping for a channel. This MUST be accessed with the indexMtx.
348
        aliasToReal map[lnwire.ShortChannelID]lnwire.ShortChannelID
349

350
        // baseIndex is a map used for option-scid-alias feature-bit links.
351
        // The value is the SCID of the link's ShortChannelID. This value may
352
        // be an alias for zero-conf channels or a confirmed SCID for
353
        // non-zero-conf channels with the option-scid-alias feature-bit. The
354
        // key includes the value itself and also any other aliases. This MUST
355
        // be accessed with the indexMtx.
356
        baseIndex map[lnwire.ShortChannelID]lnwire.ShortChannelID
357
}
358

359
// New creates the new instance of htlc switch.
360
func New(cfg Config, currentHeight uint32) (*Switch, error) {
3✔
361
        resStore := newResolutionStore(cfg.DB)
3✔
362

3✔
363
        circuitMap, err := NewCircuitMap(&CircuitMapConfig{
3✔
364
                DB:                    cfg.DB,
3✔
365
                FetchAllOpenChannels:  cfg.FetchAllOpenChannels,
3✔
366
                FetchClosedChannels:   cfg.FetchClosedChannels,
3✔
367
                ExtractErrorEncrypter: cfg.ExtractErrorEncrypter,
3✔
368
                CheckResolutionMsg:    resStore.checkResolutionMsg,
3✔
369
        })
3✔
370
        if err != nil {
3✔
371
                return nil, err
×
372
        }
×
373

374
        s := &Switch{
3✔
375
                bestHeight:        currentHeight,
3✔
376
                cfg:               &cfg,
3✔
377
                circuits:          circuitMap,
3✔
378
                linkIndex:         make(map[lnwire.ChannelID]ChannelLink),
3✔
379
                forwardingIndex:   make(map[lnwire.ShortChannelID]ChannelLink),
3✔
380
                interfaceIndex:    make(map[[33]byte]map[lnwire.ChannelID]ChannelLink),
3✔
381
                pendingLinkIndex:  make(map[lnwire.ChannelID]ChannelLink),
3✔
382
                linkStopIndex:     make(map[lnwire.ChannelID]chan struct{}),
3✔
383
                networkResults:    newNetworkResultStore(cfg.DB),
3✔
384
                htlcPlex:          make(chan *plexPacket),
3✔
385
                chanCloseRequests: make(chan *ChanClose),
3✔
386
                resolutionMsgs:    make(chan *resolutionMsg),
3✔
387
                resMsgStore:       resStore,
3✔
388
                quit:              make(chan struct{}),
3✔
389
        }
3✔
390

3✔
391
        s.aliasToReal = make(map[lnwire.ShortChannelID]lnwire.ShortChannelID)
3✔
392
        s.baseIndex = make(map[lnwire.ShortChannelID]lnwire.ShortChannelID)
3✔
393

3✔
394
        s.mailOrchestrator = newMailOrchestrator(&mailOrchConfig{
3✔
395
                forwardPackets:    s.ForwardPackets,
3✔
396
                clock:             s.cfg.Clock,
3✔
397
                expiry:            s.cfg.MailboxDeliveryTimeout,
3✔
398
                failMailboxUpdate: s.failMailboxUpdate,
3✔
399
        })
3✔
400

3✔
401
        return s, nil
3✔
402
}
403

404
// resolutionMsg is a struct that wraps an existing ResolutionMsg with a done
405
// channel. We'll use this channel to synchronize delivery of the message with
406
// the caller.
407
type resolutionMsg struct {
408
        contractcourt.ResolutionMsg
409

410
        errChan chan error
411
}
412

413
// ProcessContractResolution is called by active contract resolvers once a
414
// contract they are watching over has been fully resolved. The message carries
415
// an external signal that *would* have been sent if the outgoing channel
416
// didn't need to go to the chain in order to fulfill a contract. We'll process
417
// this message just as if it came from an active outgoing channel.
418
func (s *Switch) ProcessContractResolution(msg contractcourt.ResolutionMsg) error {
3✔
419
        errChan := make(chan error, 1)
3✔
420

3✔
421
        select {
3✔
422
        case s.resolutionMsgs <- &resolutionMsg{
423
                ResolutionMsg: msg,
424
                errChan:       errChan,
425
        }:
3✔
426
        case <-s.quit:
×
427
                return ErrSwitchExiting
×
428
        }
429

430
        select {
3✔
431
        case err := <-errChan:
3✔
432
                return err
3✔
433
        case <-s.quit:
×
434
                return ErrSwitchExiting
×
435
        }
436
}
437

438
// HasAttemptResult reads the network result store to fetch the specified
439
// attempt. Returns true if the attempt result exists.
440
func (s *Switch) HasAttemptResult(attemptID uint64) (bool, error) {
3✔
441
        _, err := s.networkResults.getResult(attemptID)
3✔
442
        if err == nil {
3✔
443
                return true, nil
×
444
        }
×
445

446
        if !errors.Is(err, ErrPaymentIDNotFound) {
3✔
447
                return false, err
×
448
        }
×
449

450
        return false, nil
3✔
451
}
452

453
// GetAttemptResult returns the result of the HTLC attempt with the given
454
// attemptID. The paymentHash should be set to the payment's overall hash, or
455
// in case of AMP payments the payment's unique identifier.
456
//
457
// The method returns a channel where the HTLC attempt result will be sent when
458
// available, or an error is encountered during forwarding. When a result is
459
// received on the channel, the HTLC is guaranteed to no longer be in flight.
460
// The switch shutting down is signaled by closing the channel. If the
461
// attemptID is unknown, ErrPaymentIDNotFound will be returned.
462
func (s *Switch) GetAttemptResult(attemptID uint64, paymentHash lntypes.Hash,
463
        deobfuscator ErrorDecrypter) (<-chan *PaymentResult, error) {
3✔
464

3✔
465
        var (
3✔
466
                nChan <-chan *networkResult
3✔
467
                err   error
3✔
468
                inKey = CircuitKey{
3✔
469
                        ChanID: hop.Source,
3✔
470
                        HtlcID: attemptID,
3✔
471
                }
3✔
472
        )
3✔
473

3✔
474
        // If the HTLC is not found in the circuit map, check whether a result
3✔
475
        // is already available.
3✔
476
        // Assumption: no one will add this attempt ID other than the caller.
3✔
477
        if s.circuits.LookupCircuit(inKey) == nil {
6✔
478
                res, err := s.networkResults.getResult(attemptID)
3✔
479
                if err != nil {
3✔
UNCOV
480
                        return nil, err
×
UNCOV
481
                }
×
482
                c := make(chan *networkResult, 1)
3✔
483
                c <- res
3✔
484
                nChan = c
3✔
485
        } else {
3✔
486
                // The HTLC was committed to the circuits, subscribe for a
3✔
487
                // result.
3✔
488
                nChan, err = s.networkResults.subscribeResult(attemptID)
3✔
489
                if err != nil {
3✔
490
                        return nil, err
×
491
                }
×
492
        }
493

494
        resultChan := make(chan *PaymentResult, 1)
3✔
495

3✔
496
        // Since the attempt was known, we can start a goroutine that can
3✔
497
        // extract the result when it is available, and pass it on to the
3✔
498
        // caller.
3✔
499
        s.wg.Add(1)
3✔
500
        go func() {
6✔
501
                defer s.wg.Done()
3✔
502

3✔
503
                var n *networkResult
3✔
504
                select {
3✔
505
                case n = <-nChan:
3✔
506
                case <-s.quit:
3✔
507
                        // We close the result channel to signal a shutdown. We
3✔
508
                        // don't send any result in this case since the HTLC is
3✔
509
                        // still in flight.
3✔
510
                        close(resultChan)
3✔
511
                        return
3✔
512
                }
513

514
                log.Debugf("Received network result %T for attemptID=%v", n.msg,
3✔
515
                        attemptID)
3✔
516

3✔
517
                // Extract the result and pass it to the result channel.
3✔
518
                result, err := s.extractResult(
3✔
519
                        deobfuscator, n, attemptID, paymentHash,
3✔
520
                )
3✔
521
                if err != nil {
3✔
522
                        e := fmt.Errorf("unable to extract result: %w", err)
×
523
                        log.Error(e)
×
524
                        resultChan <- &PaymentResult{
×
525
                                Error: e,
×
526
                        }
×
527
                        return
×
528
                }
×
529
                resultChan <- result
3✔
530
        }()
531

532
        return resultChan, nil
3✔
533
}
534

535
// CleanStore calls the underlying result store, telling it is safe to delete
536
// all entries except the ones in the keepPids map. This should be called
537
// preiodically to let the switch clean up payment results that we have
538
// handled.
539
func (s *Switch) CleanStore(keepPids map[uint64]struct{}) error {
3✔
540
        return s.networkResults.cleanStore(keepPids)
3✔
541
}
3✔
542

543
// SendHTLC is used by other subsystems which aren't belong to htlc switch
544
// package in order to send the htlc update. The attemptID used MUST be unique
545
// for this HTLC, and MUST be used only once, otherwise the switch might reject
546
// it.
547
func (s *Switch) SendHTLC(firstHop lnwire.ShortChannelID, attemptID uint64,
548
        htlc *lnwire.UpdateAddHTLC) error {
3✔
549

3✔
550
        // Generate and send new update packet, if error will be received on
3✔
551
        // this stage it means that packet haven't left boundaries of our
3✔
552
        // system and something wrong happened.
3✔
553
        packet := &htlcPacket{
3✔
554
                incomingChanID: hop.Source,
3✔
555
                incomingHTLCID: attemptID,
3✔
556
                outgoingChanID: firstHop,
3✔
557
                htlc:           htlc,
3✔
558
                amount:         htlc.Amount,
3✔
559
        }
3✔
560

3✔
561
        // Attempt to fetch the target link before creating a circuit so that
3✔
562
        // we don't leave dangling circuits. The getLocalLink method does not
3✔
563
        // require the circuit variable to be set on the *htlcPacket.
3✔
564
        link, linkErr := s.getLocalLink(packet, htlc)
3✔
565
        if linkErr != nil {
6✔
566
                // Notify the htlc notifier of a link failure on our outgoing
3✔
567
                // link. Incoming timelock/amount values are not set because
3✔
568
                // they are not present for local sends.
3✔
569
                s.cfg.HtlcNotifier.NotifyLinkFailEvent(
3✔
570
                        newHtlcKey(packet),
3✔
571
                        HtlcInfo{
3✔
572
                                OutgoingTimeLock: htlc.Expiry,
3✔
573
                                OutgoingAmt:      htlc.Amount,
3✔
574
                        },
3✔
575
                        HtlcEventTypeSend,
3✔
576
                        linkErr,
3✔
577
                        false,
3✔
578
                )
3✔
579

3✔
580
                return linkErr
3✔
581
        }
3✔
582

583
        // Evaluate whether this HTLC would bypass our fee exposure. If it
584
        // does, don't send it out and instead return an error.
585
        if s.dustExceedsFeeThreshold(link, htlc.Amount, false) {
3✔
UNCOV
586
                // Notify the htlc notifier of a link failure on our outgoing
×
UNCOV
587
                // link. We use the FailTemporaryChannelFailure in place of a
×
UNCOV
588
                // more descriptive error message.
×
UNCOV
589
                linkErr := NewLinkError(
×
UNCOV
590
                        &lnwire.FailTemporaryChannelFailure{},
×
UNCOV
591
                )
×
UNCOV
592
                s.cfg.HtlcNotifier.NotifyLinkFailEvent(
×
UNCOV
593
                        newHtlcKey(packet),
×
UNCOV
594
                        HtlcInfo{
×
UNCOV
595
                                OutgoingTimeLock: htlc.Expiry,
×
UNCOV
596
                                OutgoingAmt:      htlc.Amount,
×
UNCOV
597
                        },
×
UNCOV
598
                        HtlcEventTypeSend,
×
UNCOV
599
                        linkErr,
×
UNCOV
600
                        false,
×
UNCOV
601
                )
×
UNCOV
602

×
UNCOV
603
                return errFeeExposureExceeded
×
UNCOV
604
        }
×
605

606
        circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
3✔
607
        actions, err := s.circuits.CommitCircuits(circuit)
3✔
608
        if err != nil {
3✔
609
                log.Errorf("unable to commit circuit in switch: %v", err)
×
610
                return err
×
611
        }
×
612

613
        // Drop duplicate packet if it has already been seen.
614
        switch {
3✔
615
        case len(actions.Drops) == 1:
3✔
616
                return ErrDuplicateAdd
3✔
617

618
        case len(actions.Fails) == 1:
×
619
                return ErrLocalAddFailed
×
620
        }
621

622
        // Give the packet to the link's mailbox so that HTLC's are properly
623
        // canceled back if the mailbox timeout elapses.
624
        packet.circuit = circuit
3✔
625

3✔
626
        return link.handleSwitchPacket(packet)
3✔
627
}
628

629
// UpdateForwardingPolicies sends a message to the switch to update the
630
// forwarding policies for the set of target channels, keyed in chanPolicies.
631
//
632
// NOTE: This function is synchronous and will block until either the
633
// forwarding policies for all links have been updated, or the switch shuts
634
// down.
635
func (s *Switch) UpdateForwardingPolicies(
636
        chanPolicies map[wire.OutPoint]models.ForwardingPolicy) {
3✔
637

3✔
638
        log.Tracef("Updating link policies: %v", lnutils.SpewLogClosure(
3✔
639
                chanPolicies))
3✔
640

3✔
641
        s.indexMtx.RLock()
3✔
642

3✔
643
        // Update each link in chanPolicies.
3✔
644
        for targetLink, policy := range chanPolicies {
6✔
645
                cid := lnwire.NewChanIDFromOutPoint(targetLink)
3✔
646

3✔
647
                link, ok := s.linkIndex[cid]
3✔
648
                if !ok {
3✔
649
                        log.Debugf("Unable to find ChannelPoint(%v) to update "+
×
650
                                "link policy", targetLink)
×
651
                        continue
×
652
                }
653

654
                link.UpdateForwardingPolicy(policy)
3✔
655
        }
656

657
        s.indexMtx.RUnlock()
3✔
658
}
659

660
// IsForwardedHTLC checks for a given channel and htlc index if it is related
661
// to an opened circuit that represents a forwarded payment.
662
func (s *Switch) IsForwardedHTLC(chanID lnwire.ShortChannelID,
663
        htlcIndex uint64) bool {
3✔
664

3✔
665
        circuit := s.circuits.LookupOpenCircuit(models.CircuitKey{
3✔
666
                ChanID: chanID,
3✔
667
                HtlcID: htlcIndex,
3✔
668
        })
3✔
669
        return circuit != nil && circuit.Incoming.ChanID != hop.Source
3✔
670
}
3✔
671

672
// ForwardPackets adds a list of packets to the switch for processing. Fails
673
// and settles are added on a first past, simultaneously constructing circuits
674
// for any adds. After persisting the circuits, another pass of the adds is
675
// given to forward them through the router. The sending link's quit channel is
676
// used to prevent deadlocks when the switch stops a link in the midst of
677
// forwarding.
678
func (s *Switch) ForwardPackets(linkQuit <-chan struct{},
679
        packets ...*htlcPacket) error {
3✔
680

3✔
681
        var (
3✔
682
                // fwdChan is a buffered channel used to receive err msgs from
3✔
683
                // the htlcPlex when forwarding this batch.
3✔
684
                fwdChan = make(chan error, len(packets))
3✔
685

3✔
686
                // numSent keeps a running count of how many packets are
3✔
687
                // forwarded to the switch, which determines how many responses
3✔
688
                // we will wait for on the fwdChan..
3✔
689
                numSent int
3✔
690
        )
3✔
691

3✔
692
        // No packets, nothing to do.
3✔
693
        if len(packets) == 0 {
6✔
694
                return nil
3✔
695
        }
3✔
696

697
        // Setup a barrier to prevent the background tasks from processing
698
        // responses until this function returns to the user.
699
        var wg sync.WaitGroup
3✔
700
        wg.Add(1)
3✔
701
        defer wg.Done()
3✔
702

3✔
703
        // Before spawning the following goroutine to proxy our error responses,
3✔
704
        // check to see if we have already been issued a shutdown request. If
3✔
705
        // so, we exit early to avoid incrementing the switch's waitgroup while
3✔
706
        // it is already in the process of shutting down.
3✔
707
        select {
3✔
708
        case <-linkQuit:
2✔
709
                return nil
2✔
UNCOV
710
        case <-s.quit:
×
UNCOV
711
                return nil
×
712
        default:
3✔
713
                // Spawn a goroutine to log the errors returned from failed packets.
3✔
714
                s.wg.Add(1)
3✔
715
                go s.logFwdErrs(&numSent, &wg, fwdChan)
3✔
716
        }
717

718
        // Make a first pass over the packets, forwarding any settles or fails.
719
        // As adds are found, we create a circuit and append it to our set of
720
        // circuits to be written to disk.
721
        var circuits []*PaymentCircuit
3✔
722
        var addBatch []*htlcPacket
3✔
723
        for _, packet := range packets {
6✔
724
                switch htlc := packet.htlc.(type) {
3✔
725
                case *lnwire.UpdateAddHTLC:
3✔
726
                        circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
3✔
727
                        packet.circuit = circuit
3✔
728
                        circuits = append(circuits, circuit)
3✔
729
                        addBatch = append(addBatch, packet)
3✔
730
                default:
3✔
731
                        err := s.routeAsync(packet, fwdChan, linkQuit)
3✔
732
                        if err != nil {
3✔
UNCOV
733
                                return fmt.Errorf("failed to forward packet %w",
×
UNCOV
734
                                        err)
×
UNCOV
735
                        }
×
736
                        numSent++
3✔
737
                }
738
        }
739

740
        // If this batch did not contain any circuits to commit, we can return
741
        // early.
742
        if len(circuits) == 0 {
6✔
743
                return nil
3✔
744
        }
3✔
745

746
        // Write any circuits that we found to disk.
747
        actions, err := s.circuits.CommitCircuits(circuits...)
3✔
748
        if err != nil {
3✔
749
                log.Errorf("unable to commit circuits in switch: %v", err)
×
750
        }
×
751

752
        // Split the htlc packets by comparing an in-order seek to the head of
753
        // the added, dropped, or failed circuits.
754
        //
755
        // NOTE: This assumes each list is guaranteed to be a subsequence of the
756
        // circuits, and that the union of the sets results in the original set
757
        // of circuits.
758
        var addedPackets, failedPackets []*htlcPacket
3✔
759
        for _, packet := range addBatch {
6✔
760
                switch {
3✔
761
                case len(actions.Adds) > 0 && packet.circuit == actions.Adds[0]:
3✔
762
                        addedPackets = append(addedPackets, packet)
3✔
763
                        actions.Adds = actions.Adds[1:]
3✔
764

765
                case len(actions.Drops) > 0 && packet.circuit == actions.Drops[0]:
3✔
766
                        actions.Drops = actions.Drops[1:]
3✔
767

UNCOV
768
                case len(actions.Fails) > 0 && packet.circuit == actions.Fails[0]:
×
UNCOV
769
                        failedPackets = append(failedPackets, packet)
×
UNCOV
770
                        actions.Fails = actions.Fails[1:]
×
771
                }
772
        }
773

774
        // Now, forward any packets for circuits that were successfully added to
775
        // the switch's circuit map.
776
        for _, packet := range addedPackets {
6✔
777
                err := s.routeAsync(packet, fwdChan, linkQuit)
3✔
778
                if err != nil {
3✔
UNCOV
779
                        return fmt.Errorf("failed to forward packet %w", err)
×
UNCOV
780
                }
×
781
                numSent++
3✔
782
        }
783

784
        // Lastly, for any packets that failed, this implies that they were
785
        // left in a half added state, which can happen when recovering from
786
        // failures.
787
        if len(failedPackets) > 0 {
3✔
UNCOV
788
                var failure lnwire.FailureMessage
×
UNCOV
789
                incomingID := failedPackets[0].incomingChanID
×
UNCOV
790

×
UNCOV
791
                // If the incoming channel is an option_scid_alias channel,
×
UNCOV
792
                // then we'll need to replace the SCID in the ChannelUpdate.
×
UNCOV
793
                update := s.failAliasUpdate(incomingID, true)
×
UNCOV
794
                if update == nil {
×
UNCOV
795
                        // Fallback to the original non-option behavior.
×
UNCOV
796
                        update, err := s.cfg.FetchLastChannelUpdate(
×
UNCOV
797
                                incomingID,
×
UNCOV
798
                        )
×
UNCOV
799
                        if err != nil {
×
800
                                failure = &lnwire.FailTemporaryNodeFailure{}
×
UNCOV
801
                        } else {
×
UNCOV
802
                                failure = lnwire.NewTemporaryChannelFailure(
×
UNCOV
803
                                        update,
×
UNCOV
804
                                )
×
UNCOV
805
                        }
×
UNCOV
806
                } else {
×
UNCOV
807
                        // This is an option_scid_alias channel.
×
UNCOV
808
                        failure = lnwire.NewTemporaryChannelFailure(update)
×
UNCOV
809
                }
×
810

UNCOV
811
                linkError := NewDetailedLinkError(
×
UNCOV
812
                        failure, OutgoingFailureIncompleteForward,
×
UNCOV
813
                )
×
UNCOV
814

×
UNCOV
815
                for _, packet := range failedPackets {
×
UNCOV
816
                        // We don't handle the error here since this method
×
UNCOV
817
                        // always returns an error.
×
UNCOV
818
                        _ = s.failAddPacket(packet, linkError)
×
UNCOV
819
                }
×
820
        }
821

822
        return nil
3✔
823
}
824

825
// logFwdErrs logs any errors received on `fwdChan`.
826
func (s *Switch) logFwdErrs(num *int, wg *sync.WaitGroup, fwdChan chan error) {
3✔
827
        defer s.wg.Done()
3✔
828

3✔
829
        // Wait here until the outer function has finished persisting
3✔
830
        // and routing the packets. This guarantees we don't read from num until
3✔
831
        // the value is accurate.
3✔
832
        wg.Wait()
3✔
833

3✔
834
        numSent := *num
3✔
835
        for i := 0; i < numSent; i++ {
6✔
836
                select {
3✔
837
                case err := <-fwdChan:
3✔
838
                        if err != nil {
6✔
839
                                log.Errorf("Unhandled error while reforwarding htlc "+
3✔
840
                                        "settle/fail over htlcswitch: %v", err)
3✔
841
                        }
3✔
UNCOV
842
                case <-s.quit:
×
UNCOV
843
                        log.Errorf("unable to forward htlc packet " +
×
UNCOV
844
                                "htlc switch was stopped")
×
UNCOV
845
                        return
×
846
                }
847
        }
848
}
849

850
// routeAsync sends a packet through the htlc switch, using the provided err
851
// chan to propagate errors back to the caller. The link's quit channel is
852
// provided so that the send can be canceled if either the link or the switch
853
// receive a shutdown requuest. This method does not wait for a response from
854
// the htlcForwarder before returning.
855
func (s *Switch) routeAsync(packet *htlcPacket, errChan chan error,
856
        linkQuit <-chan struct{}) error {
3✔
857

3✔
858
        command := &plexPacket{
3✔
859
                pkt: packet,
3✔
860
                err: errChan,
3✔
861
        }
3✔
862

3✔
863
        select {
3✔
864
        case s.htlcPlex <- command:
3✔
865
                return nil
3✔
UNCOV
866
        case <-linkQuit:
×
UNCOV
867
                return ErrLinkShuttingDown
×
868
        case <-s.quit:
×
869
                return errors.New("htlc switch was stopped")
×
870
        }
871
}
872

873
// getLocalLink handles the addition of a htlc for a send that originates from
874
// our node. It returns the link that the htlc should be forwarded outwards on,
875
// and a link error if the htlc cannot be forwarded.
876
func (s *Switch) getLocalLink(pkt *htlcPacket, htlc *lnwire.UpdateAddHTLC) (
877
        ChannelLink, *LinkError) {
3✔
878

3✔
879
        // Try to find links by node destination.
3✔
880
        s.indexMtx.RLock()
3✔
881
        link, err := s.getLinkByShortID(pkt.outgoingChanID)
3✔
882
        if err != nil {
6✔
883
                // If the link was not found for the outgoingChanID, an outside
3✔
884
                // subsystem may be using the confirmed SCID of a zero-conf
3✔
885
                // channel. In this case, we'll consult the Switch maps to see
3✔
886
                // if an alias exists and use the alias to lookup the link.
3✔
887
                // This extra step is a consequence of not updating the Switch
3✔
888
                // forwardingIndex when a zero-conf channel is confirmed. We
3✔
889
                // don't need to change the outgoingChanID since the link will
3✔
890
                // do that upon receiving the packet.
3✔
891
                baseScid, ok := s.baseIndex[pkt.outgoingChanID]
3✔
892
                if !ok {
6✔
893
                        s.indexMtx.RUnlock()
3✔
894
                        log.Errorf("Link %v not found", pkt.outgoingChanID)
3✔
895
                        return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
3✔
896
                }
3✔
897

898
                // The base SCID was found, so we'll use that to fetch the
899
                // link.
900
                link, err = s.getLinkByShortID(baseScid)
3✔
901
                if err != nil {
3✔
902
                        s.indexMtx.RUnlock()
×
903
                        log.Errorf("Link %v not found", baseScid)
×
904
                        return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
×
905
                }
×
906
        }
907
        // We finished looking up the indexes, so we can unlock the mutex before
908
        // performing the link operations which might also acquire the lock
909
        // in case e.g. failAliasUpdate is called.
910
        s.indexMtx.RUnlock()
3✔
911

3✔
912
        if !link.EligibleToForward() {
3✔
UNCOV
913
                log.Errorf("Link %v is not available to forward",
×
UNCOV
914
                        pkt.outgoingChanID)
×
UNCOV
915

×
UNCOV
916
                // The update does not need to be populated as the error
×
UNCOV
917
                // will be returned back to the router.
×
UNCOV
918
                return nil, NewDetailedLinkError(
×
UNCOV
919
                        lnwire.NewTemporaryChannelFailure(nil),
×
UNCOV
920
                        OutgoingFailureLinkNotEligible,
×
UNCOV
921
                )
×
UNCOV
922
        }
×
923

924
        // Ensure that the htlc satisfies the outgoing channel policy.
925
        currentHeight := atomic.LoadUint32(&s.bestHeight)
3✔
926
        htlcErr := link.CheckHtlcTransit(
3✔
927
                htlc.PaymentHash, htlc.Amount, htlc.Expiry, currentHeight,
3✔
928
                htlc.CustomRecords,
3✔
929
        )
3✔
930
        if htlcErr != nil {
4✔
931
                log.Errorf("Link %v policy for local forward not "+
1✔
932
                        "satisfied", pkt.outgoingChanID)
1✔
933
                return nil, htlcErr
1✔
934
        }
1✔
935

936
        return link, nil
3✔
937
}
938

939
// handleLocalResponse processes a Settle or Fail responding to a
940
// locally-initiated payment. This is handled asynchronously to avoid blocking
941
// the main event loop within the switch, as these operations can require
942
// multiple db transactions. The guarantees of the circuit map are stringent
943
// enough such that we are able to tolerate reordering of these operations
944
// without side effects. The primary operations handled are:
945
//  1. Save the payment result to the pending payment store.
946
//  2. Notify subscribers about the payment result.
947
//  3. Ack settle/fail references, to avoid resending this response internally
948
//  4. Teardown the closing circuit in the circuit map
949
//
950
// NOTE: This method MUST be spawned as a goroutine.
951
func (s *Switch) handleLocalResponse(pkt *htlcPacket) {
3✔
952
        defer s.wg.Done()
3✔
953

3✔
954
        attemptID := pkt.incomingHTLCID
3✔
955

3✔
956
        // The error reason will be unencypted in case this a local
3✔
957
        // failure or a converted error.
3✔
958
        unencrypted := pkt.localFailure || pkt.convertedError
3✔
959
        n := &networkResult{
3✔
960
                msg:          pkt.htlc,
3✔
961
                unencrypted:  unencrypted,
3✔
962
                isResolution: pkt.isResolution,
3✔
963
        }
3✔
964

3✔
965
        // Store the result to the db. This will also notify subscribers about
3✔
966
        // the result.
3✔
967
        if err := s.networkResults.storeResult(attemptID, n); err != nil {
3✔
968
                log.Errorf("Unable to store attempt result for pid=%v: %v",
×
969
                        attemptID, err)
×
970
                return
×
971
        }
×
972

973
        // First, we'll clean up any fwdpkg references, circuit entries, and
974
        // mark in our db that the payment for this payment hash has either
975
        // succeeded or failed.
976
        //
977
        // If this response is contained in a forwarding package, we'll start by
978
        // acking the settle/fail so that we don't continue to retransmit the
979
        // HTLC internally.
980
        if pkt.destRef != nil {
6✔
981
                if err := s.ackSettleFail(*pkt.destRef); err != nil {
3✔
982
                        log.Warnf("Unable to ack settle/fail reference: %s: %v",
×
983
                                *pkt.destRef, err)
×
984
                        return
×
985
                }
×
986
        }
987

988
        // Next, we'll remove the circuit since we are about to complete an
989
        // fulfill/fail of this HTLC. Since we've already removed the
990
        // settle/fail fwdpkg reference, the response from the peer cannot be
991
        // replayed internally if this step fails. If this happens, this logic
992
        // will be executed when a provided resolution message comes through.
993
        // This can only happen if the circuit is still open, which is why this
994
        // ordering is chosen.
995
        if err := s.teardownCircuit(pkt); err != nil {
3✔
996
                log.Errorf("Unable to teardown circuit %s: %v",
×
997
                        pkt.inKey(), err)
×
998
                return
×
999
        }
×
1000

1001
        // Finally, notify on the htlc failure or success that has been handled.
1002
        key := newHtlcKey(pkt)
3✔
1003
        eventType := getEventType(pkt)
3✔
1004

3✔
1005
        switch htlc := pkt.htlc.(type) {
3✔
1006
        case *lnwire.UpdateFulfillHTLC:
3✔
1007
                s.cfg.HtlcNotifier.NotifySettleEvent(key, htlc.PaymentPreimage,
3✔
1008
                        eventType)
3✔
1009

1010
        case *lnwire.UpdateFailHTLC:
3✔
1011
                s.cfg.HtlcNotifier.NotifyForwardingFailEvent(key, eventType)
3✔
1012
        }
1013
}
1014

1015
// extractResult uses the given deobfuscator to extract the payment result from
1016
// the given network message.
1017
func (s *Switch) extractResult(deobfuscator ErrorDecrypter, n *networkResult,
1018
        attemptID uint64, paymentHash lntypes.Hash) (*PaymentResult, error) {
3✔
1019

3✔
1020
        switch htlc := n.msg.(type) {
3✔
1021

1022
        // We've received a settle update which means we can finalize the user
1023
        // payment and return successful response.
1024
        case *lnwire.UpdateFulfillHTLC:
3✔
1025
                return &PaymentResult{
3✔
1026
                        Preimage: htlc.PaymentPreimage,
3✔
1027
                }, nil
3✔
1028

1029
        // We've received a fail update which means we can finalize the
1030
        // user payment and return fail response.
1031
        case *lnwire.UpdateFailHTLC:
3✔
1032
                // TODO(yy): construct deobfuscator here to avoid creating it
3✔
1033
                // in paymentLifecycle even for settled HTLCs.
3✔
1034
                encryptedErr, paymentErr := s.parseFailedPayment(
3✔
1035
                        deobfuscator, attemptID, paymentHash, n.unencrypted,
3✔
1036
                        n.isResolution, htlc,
3✔
1037
                )
3✔
1038

3✔
1039
                // The failure is opaque and needs to be deferred.
3✔
1040
                if encryptedErr != nil {
6✔
1041
                        return &PaymentResult{
3✔
1042
                                EncryptedError: encryptedErr,
3✔
1043
                        }, nil
3✔
1044
                }
3✔
1045

1046
                // Otherwise, the payment failed with a known reason.
1047
                return &PaymentResult{
3✔
1048
                        Error: paymentErr,
3✔
1049
                }, nil
3✔
1050

1051
        default:
×
1052
                return nil, fmt.Errorf("received unknown response type: %T",
×
1053
                        htlc)
×
1054
        }
1055
}
1056

1057
// parseFailedPayment determines the appropriate failure message for a failed
1058
// user-initiated payment. It returns a mutually exclusive pair: either a raw,
1059
// encrypted error blob, or a decrypted error.
1060
//
1061
// The cases handled are:
1062
//  1. An unencrypted failure: This occurs when the payment fails locally before
1063
//     clearing the first link. The failure reason is already in plaintext.
1064
//  2. A resolution from the chain arbitrator: This occurs for on-chain
1065
//     timeouts, which may not have a specific failure reason.
1066
//  3. A failure from a remote hop: This is the standard case for a multi-hop
1067
//     payment failure.
1068
//     - If a deobfuscator is provided, this function will attempt to decrypt
1069
//     the failure reason.
1070
//     - If a deobfuscator is NOT provided, the function returns the raw,
1071
//     onion-encrypted failure blob. This blob is only fully decryptable by the
1072
//     entity which built the onion packet.
1073
func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
1074
        attemptID uint64, paymentHash lntypes.Hash, unencrypted,
1075
        isResolution bool, htlc *lnwire.UpdateFailHTLC) ([]byte, error) {
3✔
1076

3✔
1077
        switch {
3✔
1078

1079
        // The payment never cleared the link, so we don't need to
1080
        // decrypt the error, simply decode it them report back to the
1081
        // user.
1082
        case unencrypted:
2✔
1083
                r := bytes.NewReader(htlc.Reason)
2✔
1084
                failureMsg, err := lnwire.DecodeFailure(r, 0)
2✔
1085
                if err != nil {
2✔
1086
                        // If we could not decode the failure reason, return a link
×
1087
                        // error indicating that we failed to decode the onion.
×
1088
                        linkError := NewDetailedLinkError(
×
1089
                                // As this didn't even clear the link, we don't
×
1090
                                // need to apply an update here since it goes
×
1091
                                // directly to the router.
×
1092
                                lnwire.NewTemporaryChannelFailure(nil),
×
1093
                                OutgoingFailureDecodeError,
×
1094
                        )
×
1095

×
1096
                        log.Errorf("%v: (hash=%v, pid=%d): %v",
×
1097
                                linkError.FailureDetail.FailureString(),
×
1098
                                paymentHash, attemptID, err)
×
1099

×
1100
                        return nil, linkError
×
NEW
1101
                }
×
1102

1103
                // If we successfully decoded the failure reason, return it.
1104
                return nil, NewLinkError(failureMsg)
2✔
1105

1106
        // A payment had to be timed out on chain before it got past
1107
        // the first hop. In this case, we'll report a permanent
1108
        // channel failure as this means us, or the remote party had to
1109
        // go on chain.
1110
        case isResolution && htlc.Reason == nil:
3✔
1111
                linkError := NewDetailedLinkError(
3✔
1112
                        &lnwire.FailPermanentChannelFailure{},
3✔
1113
                        OutgoingFailureOnChainTimeout,
3✔
1114
                )
3✔
1115

3✔
1116
                log.Infof("%v: hash=%v, pid=%d",
3✔
1117
                        linkError.FailureDetail.FailureString(),
3✔
1118
                        paymentHash, attemptID)
3✔
1119

3✔
1120
                return nil, linkError
3✔
1121

1122
        // A regular multi-hop payment error that we'll need to
1123
        // decrypt.
1124
        default:
3✔
1125
                // If we don't have a deobfuscator, we cannot proceed. Return
3✔
1126
                // the encrypted reason to the caller.
3✔
1127
                if deobfuscator == nil {
6✔
1128
                        return htlc.Reason, nil
3✔
1129
                }
3✔
1130

1131
                // We'll attempt to fully decrypt the onion encrypted
1132
                // error. If we're unable to then we'll bail early.
1133
                failure, err := deobfuscator.DecryptError(htlc.Reason)
3✔
1134
                if err != nil {
3✔
UNCOV
1135
                        log.Errorf("unable to de-obfuscate onion failure "+
×
UNCOV
1136
                                "(hash=%v, pid=%d): %v",
×
UNCOV
1137
                                paymentHash, attemptID, err)
×
UNCOV
1138

×
UNCOV
1139
                        return nil, ErrUnreadableFailureMessage
×
NEW
1140
                }
×
1141

1142
                return nil, failure
3✔
1143
        }
1144
}
1145

1146
// handlePacketForward is used in cases when we need forward the htlc update
1147
// from one channel link to another and be able to propagate the settle/fail
1148
// updates back. This behaviour is achieved by creation of payment circuits.
1149
func (s *Switch) handlePacketForward(packet *htlcPacket) error {
3✔
1150
        switch htlc := packet.htlc.(type) {
3✔
1151
        // Channel link forwarded us a new htlc, therefore we initiate the
1152
        // payment circuit within our internal state so we can properly forward
1153
        // the ultimate settle message back latter.
1154
        case *lnwire.UpdateAddHTLC:
3✔
1155
                return s.handlePacketAdd(packet, htlc)
3✔
1156

1157
        case *lnwire.UpdateFulfillHTLC:
3✔
1158
                return s.handlePacketSettle(packet)
3✔
1159

1160
        // Channel link forwarded us an update_fail_htlc message.
1161
        //
1162
        // NOTE: when the channel link receives an update_fail_malformed_htlc
1163
        // from upstream, it will convert the message into update_fail_htlc and
1164
        // forward it. Thus there's no need to catch `UpdateFailMalformedHTLC`
1165
        // here.
1166
        case *lnwire.UpdateFailHTLC:
3✔
1167
                return s.handlePacketFail(packet, htlc)
3✔
1168

1169
        default:
×
1170
                return fmt.Errorf("wrong update type: %T", htlc)
×
1171
        }
1172
}
1173

1174
// checkCircularForward checks whether a forward is circular (arrives and
1175
// departs on the same link) and returns a link error if the switch is
1176
// configured to disallow this behaviour.
1177
func (s *Switch) checkCircularForward(incoming, outgoing lnwire.ShortChannelID,
1178
        allowCircular bool, paymentHash lntypes.Hash) *LinkError {
3✔
1179

3✔
1180
        log.Tracef("Checking for circular route: incoming=%v, outgoing=%v "+
3✔
1181
                "(payment hash: %x)", incoming, outgoing, paymentHash[:])
3✔
1182

3✔
1183
        // If they are equal, we can skip the alias mapping checks.
3✔
1184
        if incoming == outgoing {
3✔
UNCOV
1185
                // The switch may be configured to allow circular routes, so
×
UNCOV
1186
                // just log and return nil.
×
UNCOV
1187
                if allowCircular {
×
UNCOV
1188
                        log.Debugf("allowing circular route over link: %v "+
×
UNCOV
1189
                                "(payment hash: %x)", incoming, paymentHash)
×
UNCOV
1190
                        return nil
×
UNCOV
1191
                }
×
1192

1193
                // Otherwise, we'll return a temporary channel failure.
UNCOV
1194
                return NewDetailedLinkError(
×
UNCOV
1195
                        lnwire.NewTemporaryChannelFailure(nil),
×
UNCOV
1196
                        OutgoingFailureCircularRoute,
×
UNCOV
1197
                )
×
1198
        }
1199

1200
        // We'll fetch the "base" SCID from the baseIndex for the incoming and
1201
        // outgoing SCIDs. If either one does not have a base SCID, then the
1202
        // two channels are not equal since one will be a channel that does not
1203
        // need a mapping and SCID equality was checked above. If the "base"
1204
        // SCIDs are equal, then this is a circular route. Otherwise, it isn't.
1205
        s.indexMtx.RLock()
3✔
1206
        incomingBaseScid, ok := s.baseIndex[incoming]
3✔
1207
        if !ok {
6✔
1208
                // This channel does not use baseIndex, bail out.
3✔
1209
                s.indexMtx.RUnlock()
3✔
1210
                return nil
3✔
1211
        }
3✔
1212

1213
        outgoingBaseScid, ok := s.baseIndex[outgoing]
3✔
1214
        if !ok {
6✔
1215
                // This channel does not use baseIndex, bail out.
3✔
1216
                s.indexMtx.RUnlock()
3✔
1217
                return nil
3✔
1218
        }
3✔
1219
        s.indexMtx.RUnlock()
3✔
1220

3✔
1221
        // Check base SCID equality.
3✔
1222
        if incomingBaseScid != outgoingBaseScid {
6✔
1223
                log.Tracef("Incoming base SCID %v does not match outgoing "+
3✔
1224
                        "base SCID %v (payment hash: %x)", incomingBaseScid,
3✔
1225
                        outgoingBaseScid, paymentHash[:])
3✔
1226

3✔
1227
                // The base SCIDs are not equal so these are not the same
3✔
1228
                // channel.
3✔
1229
                return nil
3✔
1230
        }
3✔
1231

1232
        // If the incoming and outgoing link are equal, the htlc is part of a
1233
        // circular route which may be used to lock up our liquidity. If the
1234
        // switch is configured to allow circular routes, log that we are
1235
        // allowing the route then return nil.
UNCOV
1236
        if allowCircular {
×
UNCOV
1237
                log.Debugf("allowing circular route over link: %v "+
×
UNCOV
1238
                        "(payment hash: %x)", incoming, paymentHash)
×
UNCOV
1239
                return nil
×
UNCOV
1240
        }
×
1241

1242
        // If our node disallows circular routes, return a temporary channel
1243
        // failure. There is nothing wrong with the policy used by the remote
1244
        // node, so we do not include a channel update.
UNCOV
1245
        return NewDetailedLinkError(
×
UNCOV
1246
                lnwire.NewTemporaryChannelFailure(nil),
×
UNCOV
1247
                OutgoingFailureCircularRoute,
×
UNCOV
1248
        )
×
1249
}
1250

1251
// failAddPacket encrypts a fail packet back to an add packet's source.
1252
// The ciphertext will be derived from the failure message proivded by context.
1253
// This method returns the failErr if all other steps complete successfully.
1254
func (s *Switch) failAddPacket(packet *htlcPacket, failure *LinkError) error {
3✔
1255
        // Encrypt the failure so that the sender will be able to read the error
3✔
1256
        // message. Since we failed this packet, we use EncryptFirstHop to
3✔
1257
        // obfuscate the failure for their eyes only.
3✔
1258
        reason, err := packet.obfuscator.EncryptFirstHop(failure.WireMessage())
3✔
1259
        if err != nil {
3✔
1260
                err := fmt.Errorf("unable to obfuscate "+
×
1261
                        "error: %v", err)
×
1262
                log.Error(err)
×
1263
                return err
×
1264
        }
×
1265

1266
        log.Error(failure.Error())
3✔
1267

3✔
1268
        // Create a failure packet for this htlc. The full set of
3✔
1269
        // information about the htlc failure is included so that they can
3✔
1270
        // be included in link failure notifications.
3✔
1271
        failPkt := &htlcPacket{
3✔
1272
                sourceRef:       packet.sourceRef,
3✔
1273
                incomingChanID:  packet.incomingChanID,
3✔
1274
                incomingHTLCID:  packet.incomingHTLCID,
3✔
1275
                outgoingChanID:  packet.outgoingChanID,
3✔
1276
                outgoingHTLCID:  packet.outgoingHTLCID,
3✔
1277
                incomingAmount:  packet.incomingAmount,
3✔
1278
                amount:          packet.amount,
3✔
1279
                incomingTimeout: packet.incomingTimeout,
3✔
1280
                outgoingTimeout: packet.outgoingTimeout,
3✔
1281
                circuit:         packet.circuit,
3✔
1282
                obfuscator:      packet.obfuscator,
3✔
1283
                linkFailure:     failure,
3✔
1284
                htlc: &lnwire.UpdateFailHTLC{
3✔
1285
                        Reason: reason,
3✔
1286
                },
3✔
1287
        }
3✔
1288

3✔
1289
        // Route a fail packet back to the source link.
3✔
1290
        err = s.mailOrchestrator.Deliver(failPkt.incomingChanID, failPkt)
3✔
1291
        if err != nil {
3✔
1292
                err = fmt.Errorf("source chanid=%v unable to "+
×
1293
                        "handle switch packet: %v",
×
1294
                        packet.incomingChanID, err)
×
1295
                log.Error(err)
×
1296
                return err
×
1297
        }
×
1298

1299
        return failure
3✔
1300
}
1301

1302
// closeCircuit accepts a settle or fail htlc and the associated htlc packet and
1303
// attempts to determine the source that forwarded this htlc. This method will
1304
// set the incoming chan and htlc ID of the given packet if the source was
1305
// found, and will properly [re]encrypt any failure messages.
1306
func (s *Switch) closeCircuit(pkt *htlcPacket) (*PaymentCircuit, error) {
3✔
1307
        // If the packet has its source, that means it was failed locally by
3✔
1308
        // the outgoing link. We fail it here to make sure only one response
3✔
1309
        // makes it through the switch.
3✔
1310
        if pkt.hasSource {
5✔
1311
                circuit, err := s.circuits.FailCircuit(pkt.inKey())
2✔
1312
                switch err {
2✔
1313

1314
                // Circuit successfully closed.
1315
                case nil:
2✔
1316
                        return circuit, nil
2✔
1317

1318
                // Circuit was previously closed, but has not been deleted.
1319
                // We'll just drop this response until the circuit has been
1320
                // fully removed.
1321
                case ErrCircuitClosing:
×
1322
                        return nil, err
×
1323

1324
                // Failed to close circuit because it does not exist. This is
1325
                // likely because the circuit was already successfully closed.
1326
                // Since this packet failed locally, there is no forwarding
1327
                // package entry to acknowledge.
1328
                case ErrUnknownCircuit:
×
1329
                        return nil, err
×
1330

1331
                // Unexpected error.
1332
                default:
×
1333
                        return nil, err
×
1334
                }
1335
        }
1336

1337
        // Otherwise, this is packet was received from the remote party.  Use
1338
        // circuit map to find the incoming link to receive the settle/fail.
1339
        circuit, err := s.circuits.CloseCircuit(pkt.outKey())
3✔
1340
        switch err {
3✔
1341

1342
        // Open circuit successfully closed.
1343
        case nil:
3✔
1344
                pkt.incomingChanID = circuit.Incoming.ChanID
3✔
1345
                pkt.incomingHTLCID = circuit.Incoming.HtlcID
3✔
1346
                pkt.circuit = circuit
3✔
1347
                pkt.sourceRef = &circuit.AddRef
3✔
1348

3✔
1349
                pktType := "SETTLE"
3✔
1350
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
6✔
1351
                        pktType = "FAIL"
3✔
1352
                }
3✔
1353

1354
                log.Debugf("Closed completed %s circuit for %x: "+
3✔
1355
                        "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
3✔
1356
                        pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1357
                        pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1358

3✔
1359
                return circuit, nil
3✔
1360

1361
        // Circuit was previously closed, but has not been deleted. We'll just
1362
        // drop this response until the circuit has been removed.
1363
        case ErrCircuitClosing:
3✔
1364
                return nil, err
3✔
1365

1366
        // Failed to close circuit because it does not exist. This is likely
1367
        // because the circuit was already successfully closed.
1368
        case ErrUnknownCircuit:
3✔
1369
                if pkt.destRef != nil {
6✔
1370
                        // Add this SettleFailRef to the set of pending settle/fail entries
3✔
1371
                        // awaiting acknowledgement.
3✔
1372
                        s.pendingSettleFails = append(s.pendingSettleFails, *pkt.destRef)
3✔
1373
                }
3✔
1374

1375
                // If this is a settle, we will not log an error message as settles
1376
                // are expected to hit the ErrUnknownCircuit case. The only way fails
1377
                // can hit this case if the link restarts after having just sent a fail
1378
                // to the switch.
1379
                _, isSettle := pkt.htlc.(*lnwire.UpdateFulfillHTLC)
3✔
1380
                if !isSettle {
3✔
1381
                        err := fmt.Errorf("unable to find target channel "+
×
1382
                                "for HTLC fail: channel ID = %s, "+
×
1383
                                "HTLC ID = %d", pkt.outgoingChanID,
×
1384
                                pkt.outgoingHTLCID)
×
1385
                        log.Error(err)
×
1386

×
1387
                        return nil, err
×
1388
                }
×
1389

1390
                return nil, nil
3✔
1391

1392
        // Unexpected error.
1393
        default:
×
1394
                return nil, err
×
1395
        }
1396
}
1397

1398
// ackSettleFail is used by the switch to ACK any settle/fail entries in the
1399
// forwarding package of the outgoing link for a payment circuit. We do this if
1400
// we're the originator of the payment, so the link stops attempting to
1401
// re-broadcast.
1402
func (s *Switch) ackSettleFail(settleFailRefs ...channeldb.SettleFailRef) error {
3✔
1403
        return kvdb.Batch(s.cfg.DB, func(tx kvdb.RwTx) error {
6✔
1404
                return s.cfg.SwitchPackager.AckSettleFails(tx, settleFailRefs...)
3✔
1405
        })
3✔
1406
}
1407

1408
// teardownCircuit removes a pending or open circuit from the switch's circuit
1409
// map and prints useful logging statements regarding the outcome.
1410
func (s *Switch) teardownCircuit(pkt *htlcPacket) error {
3✔
1411
        var pktType string
3✔
1412
        switch htlc := pkt.htlc.(type) {
3✔
1413
        case *lnwire.UpdateFulfillHTLC:
3✔
1414
                pktType = "SETTLE"
3✔
1415
        case *lnwire.UpdateFailHTLC:
3✔
1416
                pktType = "FAIL"
3✔
1417
        default:
×
1418
                return fmt.Errorf("cannot tear down packet of type: %T", htlc)
×
1419
        }
1420

1421
        var paymentHash lntypes.Hash
3✔
1422

3✔
1423
        // Perform a defensive check to make sure we don't try to access a nil
3✔
1424
        // circuit.
3✔
1425
        circuit := pkt.circuit
3✔
1426
        if circuit != nil {
6✔
1427
                copy(paymentHash[:], circuit.PaymentHash[:])
3✔
1428
        }
3✔
1429

1430
        log.Debugf("Tearing down circuit with %s pkt, removing circuit=%v "+
3✔
1431
                "with keystone=%v", pktType, pkt.inKey(), pkt.outKey())
3✔
1432

3✔
1433
        err := s.circuits.DeleteCircuits(pkt.inKey())
3✔
1434
        if err != nil {
3✔
1435
                log.Warnf("Failed to tear down circuit (%s, %d) <-> (%s, %d) "+
×
1436
                        "with payment_hash=%v using %s pkt", pkt.incomingChanID,
×
1437
                        pkt.incomingHTLCID, pkt.outgoingChanID,
×
1438
                        pkt.outgoingHTLCID, pkt.circuit.PaymentHash, pktType)
×
1439

×
1440
                return err
×
1441
        }
×
1442

1443
        log.Debugf("Closed %s circuit for %v: (%s, %d) <-> (%s, %d)", pktType,
3✔
1444
                paymentHash, pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1445
                pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1446

3✔
1447
        return nil
3✔
1448
}
1449

1450
// CloseLink creates and sends the close channel command to the target link
1451
// directing the specified closure type. If the closure type is CloseRegular,
1452
// targetFeePerKw parameter should be the ideal fee-per-kw that will be used as
1453
// a starting point for close negotiation. The deliveryScript parameter is an
1454
// optional parameter which sets a user specified script to close out to.
1455
func (s *Switch) CloseLink(ctx context.Context, chanPoint *wire.OutPoint,
1456
        closeType contractcourt.ChannelCloseType,
1457
        targetFeePerKw, maxFee chainfee.SatPerKWeight,
1458
        deliveryScript lnwire.DeliveryAddress) (chan interface{}, chan error) {
3✔
1459

3✔
1460
        // TODO(roasbeef) abstract out the close updates.
3✔
1461
        updateChan := make(chan interface{}, 2)
3✔
1462
        errChan := make(chan error, 1)
3✔
1463

3✔
1464
        command := &ChanClose{
3✔
1465
                CloseType:      closeType,
3✔
1466
                ChanPoint:      chanPoint,
3✔
1467
                Updates:        updateChan,
3✔
1468
                TargetFeePerKw: targetFeePerKw,
3✔
1469
                DeliveryScript: deliveryScript,
3✔
1470
                Err:            errChan,
3✔
1471
                MaxFee:         maxFee,
3✔
1472
                Ctx:            ctx,
3✔
1473
        }
3✔
1474

3✔
1475
        select {
3✔
1476
        case s.chanCloseRequests <- command:
3✔
1477
                return updateChan, errChan
3✔
1478

1479
        case <-s.quit:
×
1480
                errChan <- ErrSwitchExiting
×
1481
                close(updateChan)
×
1482
                return updateChan, errChan
×
1483
        }
1484
}
1485

1486
// htlcForwarder is responsible for optimally forwarding (and possibly
1487
// fragmenting) incoming/outgoing HTLCs amongst all active interfaces and their
1488
// links. The duties of the forwarder are similar to that of a network switch,
1489
// in that it facilitates multi-hop payments by acting as a central messaging
1490
// bus. The switch communicates will active links to create, manage, and tear
1491
// down active onion routed payments. Each active channel is modeled as
1492
// networked device with metadata such as the available payment bandwidth, and
1493
// total link capacity.
1494
//
1495
// NOTE: This MUST be run as a goroutine.
1496
func (s *Switch) htlcForwarder() {
3✔
1497
        defer s.wg.Done()
3✔
1498

3✔
1499
        defer func() {
6✔
1500
                s.blockEpochStream.Cancel()
3✔
1501

3✔
1502
                // Remove all links once we've been signalled for shutdown.
3✔
1503
                var linksToStop []ChannelLink
3✔
1504
                s.indexMtx.Lock()
3✔
1505
                for _, link := range s.linkIndex {
6✔
1506
                        activeLink := s.removeLink(link.ChanID())
3✔
1507
                        if activeLink == nil {
3✔
1508
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1509
                                        "on stop", link.ChanID())
×
1510
                                continue
×
1511
                        }
1512
                        linksToStop = append(linksToStop, activeLink)
3✔
1513
                }
1514
                for _, link := range s.pendingLinkIndex {
6✔
1515
                        pendingLink := s.removeLink(link.ChanID())
3✔
1516
                        if pendingLink == nil {
3✔
1517
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1518
                                        "on stop", link.ChanID())
×
1519
                                continue
×
1520
                        }
1521
                        linksToStop = append(linksToStop, pendingLink)
3✔
1522
                }
1523
                s.indexMtx.Unlock()
3✔
1524

3✔
1525
                // Now that all pending and live links have been removed from
3✔
1526
                // the forwarding indexes, stop each one before shutting down.
3✔
1527
                // We'll shut them down in parallel to make exiting as fast as
3✔
1528
                // possible.
3✔
1529
                var wg sync.WaitGroup
3✔
1530
                for _, link := range linksToStop {
6✔
1531
                        wg.Add(1)
3✔
1532
                        go func(l ChannelLink) {
6✔
1533
                                defer wg.Done()
3✔
1534

3✔
1535
                                l.Stop()
3✔
1536
                        }(link)
3✔
1537
                }
1538
                wg.Wait()
3✔
1539

3✔
1540
                // Before we exit fully, we'll attempt to flush out any
3✔
1541
                // forwarding events that may still be lingering since the last
3✔
1542
                // batch flush.
3✔
1543
                if err := s.FlushForwardingEvents(); err != nil {
3✔
1544
                        log.Errorf("unable to flush forwarding events: %v", err)
×
1545
                }
×
1546
        }()
1547

1548
        // TODO(roasbeef): cleared vs settled distinction
1549
        var (
3✔
1550
                totalNumUpdates uint64
3✔
1551
                totalSatSent    btcutil.Amount
3✔
1552
                totalSatRecv    btcutil.Amount
3✔
1553
        )
3✔
1554
        s.cfg.LogEventTicker.Resume()
3✔
1555
        defer s.cfg.LogEventTicker.Stop()
3✔
1556

3✔
1557
        // Every 15 seconds, we'll flush out the forwarding events that
3✔
1558
        // occurred during that period.
3✔
1559
        s.cfg.FwdEventTicker.Resume()
3✔
1560
        defer s.cfg.FwdEventTicker.Stop()
3✔
1561

3✔
1562
        defer s.cfg.AckEventTicker.Stop()
3✔
1563

3✔
1564
out:
3✔
1565
        for {
6✔
1566

3✔
1567
                // If the set of pending settle/fail entries is non-zero,
3✔
1568
                // reinstate the ack ticker so we can batch ack them.
3✔
1569
                if len(s.pendingSettleFails) > 0 {
6✔
1570
                        s.cfg.AckEventTicker.Resume()
3✔
1571
                }
3✔
1572

1573
                select {
3✔
1574
                case blockEpoch, ok := <-s.blockEpochStream.Epochs:
3✔
1575
                        if !ok {
3✔
1576
                                break out
×
1577
                        }
1578

1579
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
3✔
1580

1581
                // A local close request has arrived, we'll forward this to the
1582
                // relevant link (if it exists) so the channel can be
1583
                // cooperatively closed (if possible).
1584
                case req := <-s.chanCloseRequests:
3✔
1585
                        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
3✔
1586

3✔
1587
                        s.indexMtx.RLock()
3✔
1588
                        link, ok := s.linkIndex[chanID]
3✔
1589
                        if !ok {
6✔
1590
                                s.indexMtx.RUnlock()
3✔
1591

3✔
1592
                                req.Err <- fmt.Errorf("no peer for channel with "+
3✔
1593
                                        "chan_id=%x", chanID[:])
3✔
1594
                                continue
3✔
1595
                        }
1596
                        s.indexMtx.RUnlock()
3✔
1597

3✔
1598
                        peerPub := link.PeerPubKey()
3✔
1599
                        log.Debugf("Requesting local channel close: peer=%x, "+
3✔
1600
                                "chan_id=%x", link.PeerPubKey(), chanID[:])
3✔
1601

3✔
1602
                        go s.cfg.LocalChannelClose(peerPub[:], req)
3✔
1603

1604
                case resolutionMsg := <-s.resolutionMsgs:
3✔
1605
                        // We'll persist the resolution message to the Switch's
3✔
1606
                        // resolution store.
3✔
1607
                        resMsg := resolutionMsg.ResolutionMsg
3✔
1608
                        err := s.resMsgStore.addResolutionMsg(&resMsg)
3✔
1609
                        if err != nil {
3✔
1610
                                // This will only fail if there is a database
×
1611
                                // error or a serialization error. Sending the
×
1612
                                // error prevents the contractcourt from being
×
1613
                                // in a state where it believes the send was
×
1614
                                // successful, when it wasn't.
×
1615
                                log.Errorf("unable to add resolution msg: %v",
×
1616
                                        err)
×
1617
                                resolutionMsg.errChan <- err
×
1618
                                continue
×
1619
                        }
1620

1621
                        // At this point, the resolution message has been
1622
                        // persisted. It is safe to signal success by sending
1623
                        // a nil error since the Switch will re-deliver the
1624
                        // resolution message on restart.
1625
                        resolutionMsg.errChan <- nil
3✔
1626

3✔
1627
                        // Create a htlc packet for this resolution. We do
3✔
1628
                        // not have some of the information that we'll need
3✔
1629
                        // for blinded error handling here , so we'll rely on
3✔
1630
                        // our forwarding logic to fill it in later.
3✔
1631
                        pkt := &htlcPacket{
3✔
1632
                                outgoingChanID: resolutionMsg.SourceChan,
3✔
1633
                                outgoingHTLCID: resolutionMsg.HtlcIndex,
3✔
1634
                                isResolution:   true,
3✔
1635
                        }
3✔
1636

3✔
1637
                        // Resolution messages will either be cancelling
3✔
1638
                        // backwards an existing HTLC, or settling a previously
3✔
1639
                        // outgoing HTLC. Based on this, we'll map the message
3✔
1640
                        // to the proper htlcPacket.
3✔
1641
                        if resolutionMsg.Failure != nil {
6✔
1642
                                pkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1643
                        } else {
6✔
1644
                                pkt.htlc = &lnwire.UpdateFulfillHTLC{
3✔
1645
                                        PaymentPreimage: *resolutionMsg.PreImage,
3✔
1646
                                }
3✔
1647
                        }
3✔
1648

1649
                        log.Debugf("Received outside contract resolution, "+
3✔
1650
                                "mapping to: %v", lnutils.SpewLogClosure(pkt))
3✔
1651

3✔
1652
                        // We don't check the error, as the only failure we can
3✔
1653
                        // encounter is due to the circuit already being
3✔
1654
                        // closed. This is fine, as processing this message is
3✔
1655
                        // meant to be idempotent.
3✔
1656
                        err = s.handlePacketForward(pkt)
3✔
1657
                        if err != nil {
3✔
1658
                                log.Errorf("Unable to forward resolution msg: %v", err)
×
1659
                        }
×
1660

1661
                // A new packet has arrived for forwarding, we'll interpret the
1662
                // packet concretely, then either forward it along, or
1663
                // interpret a return packet to a locally initialized one.
1664
                case cmd := <-s.htlcPlex:
3✔
1665
                        cmd.err <- s.handlePacketForward(cmd.pkt)
3✔
1666

1667
                // When this time ticks, then it indicates that we should
1668
                // collect all the forwarding events since the last internal,
1669
                // and write them out to our log.
1670
                case <-s.cfg.FwdEventTicker.Ticks():
3✔
1671
                        s.wg.Add(1)
3✔
1672
                        go func() {
6✔
1673
                                defer s.wg.Done()
3✔
1674

3✔
1675
                                if err := s.FlushForwardingEvents(); err != nil {
3✔
1676
                                        log.Errorf("Unable to flush "+
×
1677
                                                "forwarding events: %v", err)
×
1678
                                }
×
1679
                        }()
1680

1681
                // The log ticker has fired, so we'll calculate some forwarding
1682
                // stats for the last 10 seconds to display within the logs to
1683
                // users.
1684
                case <-s.cfg.LogEventTicker.Ticks():
3✔
1685
                        // First, we'll collate the current running tally of
3✔
1686
                        // our forwarding stats.
3✔
1687
                        prevSatSent := totalSatSent
3✔
1688
                        prevSatRecv := totalSatRecv
3✔
1689
                        prevNumUpdates := totalNumUpdates
3✔
1690

3✔
1691
                        var (
3✔
1692
                                newNumUpdates uint64
3✔
1693
                                newSatSent    btcutil.Amount
3✔
1694
                                newSatRecv    btcutil.Amount
3✔
1695
                        )
3✔
1696

3✔
1697
                        // Next, we'll run through all the registered links and
3✔
1698
                        // compute their up-to-date forwarding stats.
3✔
1699
                        s.indexMtx.RLock()
3✔
1700
                        for _, link := range s.linkIndex {
6✔
1701
                                // TODO(roasbeef): when links first registered
3✔
1702
                                // stats printed.
3✔
1703
                                updates, sent, recv := link.Stats()
3✔
1704
                                newNumUpdates += updates
3✔
1705
                                newSatSent += sent.ToSatoshis()
3✔
1706
                                newSatRecv += recv.ToSatoshis()
3✔
1707
                        }
3✔
1708
                        s.indexMtx.RUnlock()
3✔
1709

3✔
1710
                        var (
3✔
1711
                                diffNumUpdates uint64
3✔
1712
                                diffSatSent    btcutil.Amount
3✔
1713
                                diffSatRecv    btcutil.Amount
3✔
1714
                        )
3✔
1715

3✔
1716
                        // If this is the first time we're computing these
3✔
1717
                        // stats, then the diff is just the new value. We do
3✔
1718
                        // this in order to avoid integer underflow issues.
3✔
1719
                        if prevNumUpdates == 0 {
6✔
1720
                                diffNumUpdates = newNumUpdates
3✔
1721
                                diffSatSent = newSatSent
3✔
1722
                                diffSatRecv = newSatRecv
3✔
1723
                        } else {
6✔
1724
                                diffNumUpdates = newNumUpdates - prevNumUpdates
3✔
1725
                                diffSatSent = newSatSent - prevSatSent
3✔
1726
                                diffSatRecv = newSatRecv - prevSatRecv
3✔
1727
                        }
3✔
1728

1729
                        // If the diff of num updates is zero, then we haven't
1730
                        // forwarded anything in the last 10 seconds, so we can
1731
                        // skip this update.
1732
                        if diffNumUpdates == 0 {
6✔
1733
                                continue
3✔
1734
                        }
1735

1736
                        // If the diff of num updates is negative, then some
1737
                        // links may have been unregistered from the switch, so
1738
                        // we'll update our stats to only include our registered
1739
                        // links.
1740
                        if int64(diffNumUpdates) < 0 {
6✔
1741
                                totalNumUpdates = newNumUpdates
3✔
1742
                                totalSatSent = newSatSent
3✔
1743
                                totalSatRecv = newSatRecv
3✔
1744
                                continue
3✔
1745
                        }
1746

1747
                        // Otherwise, we'll log this diff, then accumulate the
1748
                        // new stats into the running total.
1749
                        log.Debugf("Sent %d satoshis and received %d satoshis "+
3✔
1750
                                "in the last 10 seconds (%f tx/sec)",
3✔
1751
                                diffSatSent, diffSatRecv,
3✔
1752
                                float64(diffNumUpdates)/10)
3✔
1753

3✔
1754
                        totalNumUpdates += diffNumUpdates
3✔
1755
                        totalSatSent += diffSatSent
3✔
1756
                        totalSatRecv += diffSatRecv
3✔
1757

1758
                // The ack ticker has fired so if we have any settle/fail entries
1759
                // for a forwarding package to ack, we will do so here in a batch
1760
                // db call.
1761
                case <-s.cfg.AckEventTicker.Ticks():
3✔
1762
                        // If the current set is empty, pause the ticker.
3✔
1763
                        if len(s.pendingSettleFails) == 0 {
6✔
1764
                                s.cfg.AckEventTicker.Pause()
3✔
1765
                                continue
3✔
1766
                        }
1767

1768
                        // Batch ack the settle/fail entries.
1769
                        if err := s.ackSettleFail(s.pendingSettleFails...); err != nil {
3✔
1770
                                log.Errorf("Unable to ack batch of settle/fails: %v", err)
×
1771
                                continue
×
1772
                        }
1773

1774
                        log.Tracef("Acked %d settle fails: %v",
3✔
1775
                                len(s.pendingSettleFails),
3✔
1776
                                lnutils.SpewLogClosure(s.pendingSettleFails))
3✔
1777

3✔
1778
                        // Reset the pendingSettleFails buffer while keeping acquired
3✔
1779
                        // memory.
3✔
1780
                        s.pendingSettleFails = s.pendingSettleFails[:0]
3✔
1781

1782
                case <-s.quit:
3✔
1783
                        return
3✔
1784
                }
1785
        }
1786
}
1787

1788
// Start starts all helper goroutines required for the operation of the switch.
1789
func (s *Switch) Start() error {
3✔
1790
        if !atomic.CompareAndSwapInt32(&s.started, 0, 1) {
3✔
1791
                log.Warn("Htlc Switch already started")
×
1792
                return errors.New("htlc switch already started")
×
1793
        }
×
1794

1795
        log.Infof("HTLC Switch starting")
3✔
1796

3✔
1797
        blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
1798
        if err != nil {
3✔
1799
                return err
×
1800
        }
×
1801
        s.blockEpochStream = blockEpochStream
3✔
1802

3✔
1803
        s.wg.Add(1)
3✔
1804
        go s.htlcForwarder()
3✔
1805

3✔
1806
        if err := s.reforwardResponses(); err != nil {
3✔
1807
                s.Stop()
×
1808
                log.Errorf("unable to reforward responses: %v", err)
×
1809
                return err
×
1810
        }
×
1811

1812
        if err := s.reforwardResolutions(); err != nil {
3✔
1813
                // We are already stopping so we can ignore the error.
×
1814
                _ = s.Stop()
×
1815
                log.Errorf("unable to reforward resolutions: %v", err)
×
1816
                return err
×
1817
        }
×
1818

1819
        return nil
3✔
1820
}
1821

1822
// reforwardResolutions fetches the set of resolution messages stored on-disk
1823
// and reforwards them if their circuits are still open. If the circuits have
1824
// been deleted, then we will delete the resolution message from the database.
1825
func (s *Switch) reforwardResolutions() error {
3✔
1826
        // Fetch all stored resolution messages, deleting the ones that are
3✔
1827
        // resolved.
3✔
1828
        resMsgs, err := s.resMsgStore.fetchAllResolutionMsg()
3✔
1829
        if err != nil {
3✔
1830
                return err
×
1831
        }
×
1832

1833
        switchPackets := make([]*htlcPacket, 0, len(resMsgs))
3✔
1834
        for _, resMsg := range resMsgs {
6✔
1835
                // If the open circuit no longer exists, then we can remove the
3✔
1836
                // message from the store.
3✔
1837
                outKey := CircuitKey{
3✔
1838
                        ChanID: resMsg.SourceChan,
3✔
1839
                        HtlcID: resMsg.HtlcIndex,
3✔
1840
                }
3✔
1841

3✔
1842
                if s.circuits.LookupOpenCircuit(outKey) == nil {
6✔
1843
                        // The open circuit doesn't exist.
3✔
1844
                        err := s.resMsgStore.deleteResolutionMsg(&outKey)
3✔
1845
                        if err != nil {
3✔
1846
                                return err
×
1847
                        }
×
1848

1849
                        continue
3✔
1850
                }
1851

1852
                // The circuit is still open, so we can assume that the link or
1853
                // switch (if we are the source) hasn't cleaned it up yet.
1854
                // We rely on our forwarding logic to fill in details that
1855
                // are not currently available to us.
1856
                resPkt := &htlcPacket{
3✔
1857
                        outgoingChanID: resMsg.SourceChan,
3✔
1858
                        outgoingHTLCID: resMsg.HtlcIndex,
3✔
1859
                        isResolution:   true,
3✔
1860
                }
3✔
1861

3✔
1862
                if resMsg.Failure != nil {
6✔
1863
                        resPkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1864
                } else {
3✔
1865
                        resPkt.htlc = &lnwire.UpdateFulfillHTLC{
×
1866
                                PaymentPreimage: *resMsg.PreImage,
×
1867
                        }
×
1868
                }
×
1869

1870
                switchPackets = append(switchPackets, resPkt)
3✔
1871
        }
1872

1873
        // We'll now dispatch the set of resolution messages to the proper
1874
        // destination. An error is only encountered here if the switch is
1875
        // shutting down.
1876
        if err := s.ForwardPackets(nil, switchPackets...); err != nil {
3✔
1877
                return err
×
1878
        }
×
1879

1880
        return nil
3✔
1881
}
1882

1883
// reforwardResponses for every known, non-pending channel, loads all associated
1884
// forwarding packages and reforwards any Settle or Fail HTLCs found. This is
1885
// used to resurrect the switch's mailboxes after a restart. This also runs for
1886
// waiting close channels since there may be settles or fails that need to be
1887
// reforwarded before they completely close.
1888
func (s *Switch) reforwardResponses() error {
3✔
1889
        openChannels, err := s.cfg.FetchAllChannels()
3✔
1890
        if err != nil {
3✔
1891
                return err
×
1892
        }
×
1893

1894
        for _, openChannel := range openChannels {
6✔
1895
                shortChanID := openChannel.ShortChanID()
3✔
1896

3✔
1897
                // Locally-initiated payments never need reforwarding.
3✔
1898
                if shortChanID == hop.Source {
6✔
1899
                        continue
3✔
1900
                }
1901

1902
                // If the channel is pending, it should have no forwarding
1903
                // packages, and nothing to reforward.
1904
                if openChannel.IsPending {
3✔
1905
                        continue
×
1906
                }
1907

1908
                // Channels in open or waiting-close may still have responses in
1909
                // their forwarding packages. We will continue to reattempt
1910
                // forwarding on startup until the channel is fully-closed.
1911
                //
1912
                // Load this channel's forwarding packages, and deliver them to
1913
                // the switch.
1914
                fwdPkgs, err := s.loadChannelFwdPkgs(shortChanID)
3✔
1915
                if err != nil {
3✔
1916
                        log.Errorf("unable to load forwarding "+
×
1917
                                "packages for %v: %v", shortChanID, err)
×
1918
                        return err
×
1919
                }
×
1920

1921
                s.reforwardSettleFails(fwdPkgs)
3✔
1922
        }
1923

1924
        return nil
3✔
1925
}
1926

1927
// loadChannelFwdPkgs loads all forwarding packages owned by the `source` short
1928
// channel identifier.
1929
func (s *Switch) loadChannelFwdPkgs(source lnwire.ShortChannelID) ([]*channeldb.FwdPkg, error) {
3✔
1930

3✔
1931
        var fwdPkgs []*channeldb.FwdPkg
3✔
1932
        if err := kvdb.View(s.cfg.DB, func(tx kvdb.RTx) error {
6✔
1933
                var err error
3✔
1934
                fwdPkgs, err = s.cfg.SwitchPackager.LoadChannelFwdPkgs(
3✔
1935
                        tx, source,
3✔
1936
                )
3✔
1937
                return err
3✔
1938
        }, func() {
6✔
1939
                fwdPkgs = nil
3✔
1940
        }); err != nil {
3✔
1941
                return nil, err
×
1942
        }
×
1943

1944
        return fwdPkgs, nil
3✔
1945
}
1946

1947
// reforwardSettleFails parses the Settle and Fail HTLCs from the list of
1948
// forwarding packages, and reforwards those that have not been acknowledged.
1949
// This is intended to occur on startup, in order to recover the switch's
1950
// mailboxes, and to ensure that responses can be propagated in case the
1951
// outgoing link never comes back online.
1952
//
1953
// NOTE: This should mimic the behavior processRemoteSettleFails.
1954
func (s *Switch) reforwardSettleFails(fwdPkgs []*channeldb.FwdPkg) {
3✔
1955
        for _, fwdPkg := range fwdPkgs {
6✔
1956
                switchPackets := make([]*htlcPacket, 0, len(fwdPkg.SettleFails))
3✔
1957
                for i, update := range fwdPkg.SettleFails {
6✔
1958
                        // Skip any settles or fails that have already been
3✔
1959
                        // acknowledged by the incoming link that originated the
3✔
1960
                        // forwarded Add.
3✔
1961
                        if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
6✔
1962
                                continue
3✔
1963
                        }
1964

1965
                        switch msg := update.UpdateMsg.(type) {
3✔
1966
                        // A settle for an HTLC we previously forwarded HTLC has
1967
                        // been received. So we'll forward the HTLC to the
1968
                        // switch which will handle propagating the settle to
1969
                        // the prior hop.
1970
                        case *lnwire.UpdateFulfillHTLC:
3✔
1971
                                destRef := fwdPkg.DestRef(uint16(i))
3✔
1972
                                settlePacket := &htlcPacket{
3✔
1973
                                        outgoingChanID: fwdPkg.Source,
3✔
1974
                                        outgoingHTLCID: msg.ID,
3✔
1975
                                        destRef:        &destRef,
3✔
1976
                                        htlc:           msg,
3✔
1977
                                }
3✔
1978

3✔
1979
                                // Add the packet to the batch to be forwarded, and
3✔
1980
                                // notify the overflow queue that a spare spot has been
3✔
1981
                                // freed up within the commitment state.
3✔
1982
                                switchPackets = append(switchPackets, settlePacket)
3✔
1983

1984
                        // A failureCode message for a previously forwarded HTLC has been
1985
                        // received. As a result a new slot will be freed up in our
1986
                        // commitment state, so we'll forward this to the switch so the
1987
                        // backwards undo can continue.
1988
                        case *lnwire.UpdateFailHTLC:
×
1989
                                // Fetch the reason the HTLC was canceled so
×
1990
                                // we can continue to propagate it. This
×
1991
                                // failure originated from another node, so
×
1992
                                // the linkFailure field is not set on this
×
1993
                                // packet. We rely on the link to fill in
×
1994
                                // additional circuit information for us.
×
1995
                                failPacket := &htlcPacket{
×
1996
                                        outgoingChanID: fwdPkg.Source,
×
1997
                                        outgoingHTLCID: msg.ID,
×
1998
                                        destRef: &channeldb.SettleFailRef{
×
1999
                                                Source: fwdPkg.Source,
×
2000
                                                Height: fwdPkg.Height,
×
2001
                                                Index:  uint16(i),
×
2002
                                        },
×
2003
                                        htlc: msg,
×
2004
                                }
×
2005

×
2006
                                // Add the packet to the batch to be forwarded, and
×
2007
                                // notify the overflow queue that a spare spot has been
×
2008
                                // freed up within the commitment state.
×
2009
                                switchPackets = append(switchPackets, failPacket)
×
2010
                        }
2011
                }
2012

2013
                // Since this send isn't tied to a specific link, we pass a nil
2014
                // link quit channel, meaning the send will fail only if the
2015
                // switch receives a shutdown request.
2016
                if err := s.ForwardPackets(nil, switchPackets...); err != nil {
3✔
2017
                        log.Errorf("Unhandled error while reforwarding packets "+
×
2018
                                "settle/fail over htlcswitch: %v", err)
×
2019
                }
×
2020
        }
2021
}
2022

2023
// Stop gracefully stops all active helper goroutines, then waits until they've
2024
// exited.
2025
func (s *Switch) Stop() error {
3✔
2026
        if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
3✔
UNCOV
2027
                log.Warn("Htlc Switch already stopped")
×
UNCOV
2028
                return errors.New("htlc switch already shutdown")
×
UNCOV
2029
        }
×
2030

2031
        log.Info("HTLC Switch shutting down...")
3✔
2032
        defer log.Debug("HTLC Switch shutdown complete")
3✔
2033

3✔
2034
        close(s.quit)
3✔
2035

3✔
2036
        s.wg.Wait()
3✔
2037

3✔
2038
        // Wait until all active goroutines have finished exiting before
3✔
2039
        // stopping the mailboxes, otherwise the mailbox map could still be
3✔
2040
        // accessed and modified.
3✔
2041
        s.mailOrchestrator.Stop()
3✔
2042

3✔
2043
        return nil
3✔
2044
}
2045

2046
// CreateAndAddLink will create a link and then add it to the internal maps
2047
// when given a ChannelLinkConfig and LightningChannel.
2048
func (s *Switch) CreateAndAddLink(linkCfg ChannelLinkConfig,
2049
        lnChan *lnwallet.LightningChannel) error {
3✔
2050

3✔
2051
        link := NewChannelLink(linkCfg, lnChan)
3✔
2052
        return s.AddLink(link)
3✔
2053
}
3✔
2054

2055
// AddLink is used to initiate the handling of the add link command. The
2056
// request will be propagated and handled in the main goroutine.
2057
func (s *Switch) AddLink(link ChannelLink) error {
3✔
2058
        s.indexMtx.Lock()
3✔
2059
        defer s.indexMtx.Unlock()
3✔
2060

3✔
2061
        chanID := link.ChanID()
3✔
2062

3✔
2063
        // First, ensure that this link is not already active in the switch.
3✔
2064
        _, err := s.getLink(chanID)
3✔
2065
        if err == nil {
3✔
UNCOV
2066
                return fmt.Errorf("unable to add ChannelLink(%v), already "+
×
UNCOV
2067
                        "active", chanID)
×
UNCOV
2068
        }
×
2069

2070
        // Get and attach the mailbox for this link, which buffers packets in
2071
        // case there packets that we tried to deliver while this link was
2072
        // offline.
2073
        shortChanID := link.ShortChanID()
3✔
2074
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(chanID, shortChanID)
3✔
2075
        link.AttachMailBox(mailbox)
3✔
2076

3✔
2077
        // Attach the Switch's failAliasUpdate function to the link.
3✔
2078
        link.attachFailAliasUpdate(s.failAliasUpdate)
3✔
2079

3✔
2080
        if err := link.Start(); err != nil {
3✔
2081
                log.Errorf("AddLink failed to start link with chanID=%v: %v",
×
2082
                        chanID, err)
×
2083
                s.removeLink(chanID)
×
2084
                return err
×
2085
        }
×
2086

2087
        if shortChanID == hop.Source {
6✔
2088
                log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
3✔
2089
                        chanID, shortChanID)
3✔
2090

3✔
2091
                s.pendingLinkIndex[chanID] = link
3✔
2092
        } else {
6✔
2093
                log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
3✔
2094
                        chanID, shortChanID)
3✔
2095

3✔
2096
                s.addLiveLink(link)
3✔
2097
                s.mailOrchestrator.BindLiveShortChanID(
3✔
2098
                        mailbox, chanID, shortChanID,
3✔
2099
                )
3✔
2100
        }
3✔
2101

2102
        return nil
3✔
2103
}
2104

2105
// addLiveLink adds a link to all associated forwarding index, this makes it a
2106
// candidate for forwarding HTLCs.
2107
func (s *Switch) addLiveLink(link ChannelLink) {
3✔
2108
        linkScid := link.ShortChanID()
3✔
2109

3✔
2110
        // We'll add the link to the linkIndex which lets us quickly
3✔
2111
        // look up a channel when we need to close or register it, and
3✔
2112
        // the forwarding index which'll be used when forwarding HTLC's
3✔
2113
        // in the multi-hop setting.
3✔
2114
        s.linkIndex[link.ChanID()] = link
3✔
2115
        s.forwardingIndex[linkScid] = link
3✔
2116

3✔
2117
        // Next we'll add the link to the interface index so we can
3✔
2118
        // quickly look up all the channels for a particular node.
3✔
2119
        peerPub := link.PeerPubKey()
3✔
2120
        if _, ok := s.interfaceIndex[peerPub]; !ok {
6✔
2121
                s.interfaceIndex[peerPub] = make(map[lnwire.ChannelID]ChannelLink)
3✔
2122
        }
3✔
2123
        s.interfaceIndex[peerPub][link.ChanID()] = link
3✔
2124

3✔
2125
        s.updateLinkAliases(link)
3✔
2126
}
2127

2128
// UpdateLinkAliases is the externally exposed wrapper for updating link
2129
// aliases. It acquires the indexMtx and calls the internal method.
2130
func (s *Switch) UpdateLinkAliases(link ChannelLink) {
3✔
2131
        s.indexMtx.Lock()
3✔
2132
        defer s.indexMtx.Unlock()
3✔
2133

3✔
2134
        s.updateLinkAliases(link)
3✔
2135
}
3✔
2136

2137
// updateLinkAliases updates the aliases for a given link. This will cause the
2138
// htlcswitch to consult the alias manager on the up to date values of its
2139
// alias maps.
2140
//
2141
// NOTE: this MUST be called with the indexMtx held.
2142
func (s *Switch) updateLinkAliases(link ChannelLink) {
3✔
2143
        linkScid := link.ShortChanID()
3✔
2144

3✔
2145
        aliases := link.getAliases()
3✔
2146
        if link.isZeroConf() {
6✔
2147
                if link.zeroConfConfirmed() {
6✔
2148
                        // Since the zero-conf channel has confirmed, we can
3✔
2149
                        // populate the aliasToReal mapping.
3✔
2150
                        confirmedScid := link.confirmedScid()
3✔
2151

3✔
2152
                        for _, alias := range aliases {
6✔
2153
                                s.aliasToReal[alias] = confirmedScid
3✔
2154
                        }
3✔
2155

2156
                        // Add the confirmed SCID as a key in the baseIndex.
2157
                        s.baseIndex[confirmedScid] = linkScid
3✔
2158
                }
2159

2160
                // Now we populate the baseIndex which will be used to fetch
2161
                // the link given any of the channel's alias SCIDs or the real
2162
                // SCID. The link's SCID is an alias, so we don't need to
2163
                // special-case it like the option-scid-alias feature-bit case
2164
                // further down.
2165
                for _, alias := range aliases {
6✔
2166
                        s.baseIndex[alias] = linkScid
3✔
2167
                }
3✔
2168
        } else if link.negotiatedAliasFeature() {
6✔
2169
                // First, we flush any alias mappings for this link's scid
3✔
2170
                // before we populate the map again, in order to get rid of old
3✔
2171
                // values that no longer exist.
3✔
2172
                for alias, real := range s.aliasToReal {
6✔
2173
                        if real == linkScid {
6✔
2174
                                delete(s.aliasToReal, alias)
3✔
2175
                        }
3✔
2176
                }
2177

2178
                for alias, real := range s.baseIndex {
6✔
2179
                        if real == linkScid {
6✔
2180
                                delete(s.baseIndex, alias)
3✔
2181
                        }
3✔
2182
                }
2183

2184
                // The link's SCID is the confirmed SCID for non-zero-conf
2185
                // option-scid-alias feature bit channels.
2186
                for _, alias := range aliases {
6✔
2187
                        s.aliasToReal[alias] = linkScid
3✔
2188
                        s.baseIndex[alias] = linkScid
3✔
2189
                }
3✔
2190

2191
                // Since the link's SCID is confirmed, it was not included in
2192
                // the baseIndex above as a key. Add it now.
2193
                s.baseIndex[linkScid] = linkScid
3✔
2194
        }
2195
}
2196

2197
// GetLink is used to initiate the handling of the get link command. The
2198
// request will be propagated/handled to/in the main goroutine.
2199
func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelUpdateHandler,
2200
        error) {
3✔
2201

3✔
2202
        s.indexMtx.RLock()
3✔
2203
        defer s.indexMtx.RUnlock()
3✔
2204

3✔
2205
        return s.getLink(chanID)
3✔
2206
}
3✔
2207

2208
// getLink returns the link stored in either the pending index or the live
2209
// lindex.
2210
func (s *Switch) getLink(chanID lnwire.ChannelID) (ChannelLink, error) {
3✔
2211
        link, ok := s.linkIndex[chanID]
3✔
2212
        if !ok {
6✔
2213
                link, ok = s.pendingLinkIndex[chanID]
3✔
2214
                if !ok {
6✔
2215
                        return nil, ErrChannelLinkNotFound
3✔
2216
                }
3✔
2217
        }
2218

2219
        return link, nil
3✔
2220
}
2221

2222
// GetLinkByShortID attempts to return the link which possesses the target short
2223
// channel ID.
2224
func (s *Switch) GetLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink,
2225
        error) {
3✔
2226

3✔
2227
        s.indexMtx.RLock()
3✔
2228
        defer s.indexMtx.RUnlock()
3✔
2229

3✔
2230
        link, err := s.getLinkByShortID(chanID)
3✔
2231
        if err != nil {
6✔
2232
                // If we failed to find the link under the passed-in SCID, we
3✔
2233
                // consult the Switch's baseIndex map to see if the confirmed
3✔
2234
                // SCID was used for a zero-conf channel.
3✔
2235
                aliasID, ok := s.baseIndex[chanID]
3✔
2236
                if !ok {
6✔
2237
                        return nil, err
3✔
2238
                }
3✔
2239

2240
                // An alias was found, use it to lookup if a link exists.
2241
                return s.getLinkByShortID(aliasID)
3✔
2242
        }
2243

2244
        return link, nil
3✔
2245
}
2246

2247
// getLinkByShortID attempts to return the link which possesses the target
2248
// short channel ID.
2249
//
2250
// NOTE: This MUST be called with the indexMtx held.
2251
func (s *Switch) getLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink, error) {
3✔
2252
        link, ok := s.forwardingIndex[chanID]
3✔
2253
        if !ok {
6✔
2254
                log.Debugf("Link not found in forwarding index using "+
3✔
2255
                        "chanID=%v", chanID)
3✔
2256

3✔
2257
                return nil, ErrChannelLinkNotFound
3✔
2258
        }
3✔
2259

2260
        return link, nil
3✔
2261
}
2262

2263
// getLinkByMapping attempts to fetch the link via the htlcPacket's
2264
// outgoingChanID, possibly using a mapping. If it finds the link via mapping,
2265
// the outgoingChanID will be changed so that an error can be properly
2266
// attributed when looping over linkErrs in handlePacketForward.
2267
//
2268
// * If the outgoingChanID is an alias, we'll fetch the link regardless if it's
2269
// public or not.
2270
//
2271
// * If the outgoingChanID is a confirmed SCID, we'll need to do more checks.
2272
//   - If there is no entry found in baseIndex, fetch the link. This channel
2273
//     did not have the option-scid-alias feature negotiated (which includes
2274
//     zero-conf and option-scid-alias channel-types).
2275
//   - If there is an entry found, fetch the link from forwardingIndex and
2276
//     fail if this is a private link.
2277
//
2278
// NOTE: This MUST be called with the indexMtx read lock held.
2279
func (s *Switch) getLinkByMapping(pkt *htlcPacket) (ChannelLink, error) {
3✔
2280
        // Determine if this ShortChannelID is an alias or a confirmed SCID.
3✔
2281
        chanID := pkt.outgoingChanID
3✔
2282
        aliasID := s.cfg.IsAlias(chanID)
3✔
2283

3✔
2284
        log.Debugf("Querying outgoing link using chanID=%v, aliasID=%v", chanID,
3✔
2285
                aliasID)
3✔
2286

3✔
2287
        // Set the originalOutgoingChanID so the proper channel_update can be
3✔
2288
        // sent back if the option-scid-alias feature bit was negotiated.
3✔
2289
        pkt.originalOutgoingChanID = chanID
3✔
2290

3✔
2291
        if aliasID {
6✔
2292
                // Since outgoingChanID is an alias, we'll fetch the link via
3✔
2293
                // baseIndex.
3✔
2294
                baseScid, ok := s.baseIndex[chanID]
3✔
2295
                if !ok {
3✔
2296
                        // No mapping exists, bail.
×
2297
                        return nil, ErrChannelLinkNotFound
×
2298
                }
×
2299

2300
                // A mapping exists, so use baseScid to find the link in the
2301
                // forwardingIndex.
2302
                link, ok := s.forwardingIndex[baseScid]
3✔
2303
                if !ok {
3✔
2304
                        log.Debugf("Forwarding index not found using "+
×
2305
                                "baseScid=%v", baseScid)
×
2306

×
2307
                        // Link not found, bail.
×
2308
                        return nil, ErrChannelLinkNotFound
×
2309
                }
×
2310

2311
                // Change the packet's outgoingChanID field so that errors are
2312
                // properly attributed.
2313
                pkt.outgoingChanID = baseScid
3✔
2314

3✔
2315
                // Return the link without checking if it's private or not.
3✔
2316
                return link, nil
3✔
2317
        }
2318

2319
        // The outgoingChanID is a confirmed SCID. Attempt to fetch the base
2320
        // SCID from baseIndex.
2321
        baseScid, ok := s.baseIndex[chanID]
3✔
2322
        if !ok {
6✔
2323
                // outgoingChanID is not a key in base index meaning this
3✔
2324
                // channel did not have the option-scid-alias feature bit
3✔
2325
                // negotiated. We'll fetch the link and return it.
3✔
2326
                link, ok := s.forwardingIndex[chanID]
3✔
2327
                if !ok {
6✔
2328
                        log.Debugf("Forwarding index not found using "+
3✔
2329
                                "chanID=%v", chanID)
3✔
2330

3✔
2331
                        // The link wasn't found, bail out.
3✔
2332
                        return nil, ErrChannelLinkNotFound
3✔
2333
                }
3✔
2334

2335
                return link, nil
3✔
2336
        }
2337

2338
        // Fetch the link whose internal SCID is baseScid.
2339
        link, ok := s.forwardingIndex[baseScid]
3✔
2340
        if !ok {
3✔
2341
                log.Debugf("Forwarding index not found using baseScid=%v",
×
2342
                        baseScid)
×
2343

×
2344
                // Link wasn't found, bail out.
×
2345
                return nil, ErrChannelLinkNotFound
×
2346
        }
×
2347

2348
        // If the link is unadvertised, we fail since the real SCID was used to
2349
        // forward over it and this is a channel where the option-scid-alias
2350
        // feature bit was negotiated.
2351
        if link.IsUnadvertised() {
3✔
UNCOV
2352
                log.Debugf("Link is unadvertised, chanID=%v, baseScid=%v",
×
UNCOV
2353
                        chanID, baseScid)
×
UNCOV
2354

×
UNCOV
2355
                return nil, ErrChannelLinkNotFound
×
UNCOV
2356
        }
×
2357

2358
        // The link is public so the confirmed SCID can be used to forward over
2359
        // it. We'll also replace pkt's outgoingChanID field so errors can
2360
        // properly be attributed in the calling function.
2361
        pkt.outgoingChanID = baseScid
3✔
2362
        return link, nil
3✔
2363
}
2364

2365
// HasActiveLink returns true if the given channel ID has a link in the link
2366
// index AND the link is eligible to forward.
2367
func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
3✔
2368
        s.indexMtx.RLock()
3✔
2369
        defer s.indexMtx.RUnlock()
3✔
2370

3✔
2371
        if link, ok := s.linkIndex[chanID]; ok {
6✔
2372
                return link.EligibleToForward()
3✔
2373
        }
3✔
2374

2375
        return false
3✔
2376
}
2377

2378
// RemoveLink purges the switch of any link associated with chanID. If a pending
2379
// or active link is not found, this method does nothing. Otherwise, the method
2380
// returns after the link has been completely shutdown.
2381
func (s *Switch) RemoveLink(chanID lnwire.ChannelID) {
3✔
2382
        s.indexMtx.Lock()
3✔
2383
        link, err := s.getLink(chanID)
3✔
2384
        if err != nil {
6✔
2385
                // If err is non-nil, this means that link is also nil. The
3✔
2386
                // link variable cannot be nil without err being non-nil.
3✔
2387
                s.indexMtx.Unlock()
3✔
2388
                log.Tracef("Unable to remove link for ChannelID(%v): %v",
3✔
2389
                        chanID, err)
3✔
2390
                return
3✔
2391
        }
3✔
2392

2393
        // Check if the link is already stopping and grab the stop chan if it
2394
        // is.
2395
        stopChan, ok := s.linkStopIndex[chanID]
3✔
2396
        if !ok {
6✔
2397
                // If the link is non-nil, it is not currently stopping, so
3✔
2398
                // we'll add a stop chan to the linkStopIndex.
3✔
2399
                stopChan = make(chan struct{})
3✔
2400
                s.linkStopIndex[chanID] = stopChan
3✔
2401
        }
3✔
2402
        s.indexMtx.Unlock()
3✔
2403

3✔
2404
        if ok {
3✔
2405
                // If the stop chan exists, we will wait for it to be closed.
×
2406
                // Once it is closed, we will exit.
×
2407
                select {
×
2408
                case <-stopChan:
×
2409
                        return
×
2410
                case <-s.quit:
×
2411
                        return
×
2412
                }
2413
        }
2414

2415
        // Stop the link before removing it from the maps.
2416
        link.Stop()
3✔
2417

3✔
2418
        s.indexMtx.Lock()
3✔
2419
        _ = s.removeLink(chanID)
3✔
2420

3✔
2421
        // Close stopChan and remove this link from the linkStopIndex.
3✔
2422
        // Deleting from the index and removing from the link must be done
3✔
2423
        // in the same block while the mutex is held.
3✔
2424
        close(stopChan)
3✔
2425
        delete(s.linkStopIndex, chanID)
3✔
2426
        s.indexMtx.Unlock()
3✔
2427
}
2428

2429
// removeLink is used to remove and stop the channel link.
2430
//
2431
// NOTE: This MUST be called with the indexMtx held.
2432
func (s *Switch) removeLink(chanID lnwire.ChannelID) ChannelLink {
3✔
2433
        log.Infof("Removing channel link with ChannelID(%v)", chanID)
3✔
2434

3✔
2435
        link, err := s.getLink(chanID)
3✔
2436
        if err != nil {
3✔
2437
                return nil
×
2438
        }
×
2439

2440
        // Remove the channel from live link indexes.
2441
        delete(s.pendingLinkIndex, link.ChanID())
3✔
2442
        delete(s.linkIndex, link.ChanID())
3✔
2443
        delete(s.forwardingIndex, link.ShortChanID())
3✔
2444

3✔
2445
        // If the link has been added to the peer index, then we'll move to
3✔
2446
        // delete the entry within the index.
3✔
2447
        peerPub := link.PeerPubKey()
3✔
2448
        if peerIndex, ok := s.interfaceIndex[peerPub]; ok {
6✔
2449
                delete(peerIndex, link.ChanID())
3✔
2450

3✔
2451
                // If after deletion, there are no longer any links, then we'll
3✔
2452
                // remove the interface map all together.
3✔
2453
                if len(peerIndex) == 0 {
6✔
2454
                        delete(s.interfaceIndex, peerPub)
3✔
2455
                }
3✔
2456
        }
2457

2458
        return link
3✔
2459
}
2460

2461
// UpdateShortChanID locates the link with the passed-in chanID and updates the
2462
// underlying channel state. This is only used in zero-conf channels to allow
2463
// the confirmed SCID to be updated.
2464
func (s *Switch) UpdateShortChanID(chanID lnwire.ChannelID) error {
3✔
2465
        s.indexMtx.Lock()
3✔
2466
        defer s.indexMtx.Unlock()
3✔
2467

3✔
2468
        // Locate the target link in the link index. If no such link exists,
3✔
2469
        // then we will ignore the request.
3✔
2470
        link, ok := s.linkIndex[chanID]
3✔
2471
        if !ok {
3✔
2472
                return fmt.Errorf("link %v not found", chanID)
×
2473
        }
×
2474

2475
        // Try to update the link's underlying channel state, returning early
2476
        // if this update failed.
2477
        _, err := link.UpdateShortChanID()
3✔
2478
        if err != nil {
3✔
2479
                return err
×
2480
        }
×
2481

2482
        // Since the zero-conf channel is confirmed, we should populate the
2483
        // aliasToReal map and update the baseIndex.
2484
        aliases := link.getAliases()
3✔
2485

3✔
2486
        confirmedScid := link.confirmedScid()
3✔
2487

3✔
2488
        for _, alias := range aliases {
6✔
2489
                s.aliasToReal[alias] = confirmedScid
3✔
2490
        }
3✔
2491

2492
        s.baseIndex[confirmedScid] = link.ShortChanID()
3✔
2493

3✔
2494
        return nil
3✔
2495
}
2496

2497
// GetLinksByInterface fetches all the links connected to a particular node
2498
// identified by the serialized compressed form of its public key.
2499
func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
2500
        error) {
3✔
2501

3✔
2502
        s.indexMtx.RLock()
3✔
2503
        defer s.indexMtx.RUnlock()
3✔
2504

3✔
2505
        var handlers []ChannelUpdateHandler
3✔
2506

3✔
2507
        links, err := s.getLinks(hop)
3✔
2508
        if err != nil {
6✔
2509
                return nil, err
3✔
2510
        }
3✔
2511

2512
        // Range over the returned []ChannelLink to convert them into
2513
        // []ChannelUpdateHandler.
2514
        for _, link := range links {
6✔
2515
                handlers = append(handlers, link)
3✔
2516
        }
3✔
2517

2518
        return handlers, nil
3✔
2519
}
2520

2521
// GetLinksByPubkey fetches all the links connected to a particular node
2522
// identified by the serialized compressed form of its public key.
2523
func (s *Switch) GetLinksByPubkey(hop [33]byte) ([]ChannelInfoProvider,
2524
        error) {
3✔
2525

3✔
2526
        s.indexMtx.RLock()
3✔
2527
        defer s.indexMtx.RUnlock()
3✔
2528

3✔
2529
        links, err := s.getLinks(hop)
3✔
2530
        if err != nil {
3✔
NEW
2531
                return nil, err
×
NEW
2532
        }
×
2533

2534
        handlers := make([]ChannelInfoProvider, 0, len(links))
3✔
2535

3✔
2536
        // Range over the returned []ChannelLink to convert them into
3✔
2537
        // []ChannelUpdateHandler.
3✔
2538
        for _, link := range links {
6✔
2539
                handlers = append(handlers, link)
3✔
2540
        }
3✔
2541

2542
        return handlers, nil
3✔
2543
}
2544

2545
// getLinks is function which returns the channel links of the peer by hop
2546
// destination id.
2547
//
2548
// NOTE: This MUST be called with the indexMtx held.
2549
func (s *Switch) getLinks(destination [33]byte) ([]ChannelLink, error) {
3✔
2550
        links, ok := s.interfaceIndex[destination]
3✔
2551
        if !ok {
6✔
2552
                return nil, ErrNoLinksFound
3✔
2553
        }
3✔
2554

2555
        channelLinks := make([]ChannelLink, 0, len(links))
3✔
2556
        for _, link := range links {
6✔
2557
                channelLinks = append(channelLinks, link)
3✔
2558
        }
3✔
2559

2560
        return channelLinks, nil
3✔
2561
}
2562

2563
// CircuitModifier returns a reference to subset of the interfaces provided by
2564
// the circuit map, to allow links to open and close circuits.
2565
func (s *Switch) CircuitModifier() CircuitModifier {
3✔
2566
        return s.circuits
3✔
2567
}
3✔
2568

2569
// CircuitLookup returns a reference to subset of the interfaces provided by the
2570
// circuit map, to allow looking up circuits.
2571
func (s *Switch) CircuitLookup() CircuitLookup {
3✔
2572
        return s.circuits
3✔
2573
}
3✔
2574

2575
// commitCircuits persistently adds a circuit to the switch's circuit map.
2576
func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
UNCOV
2577
        *CircuitFwdActions, error) {
×
UNCOV
2578

×
UNCOV
2579
        return s.circuits.CommitCircuits(circuits...)
×
UNCOV
2580
}
×
2581

2582
// FlushForwardingEvents flushes out the set of pending forwarding events to
2583
// the persistent log. This will be used by the switch to periodically flush
2584
// out the set of forwarding events to disk. External callers can also use this
2585
// method to ensure all data is flushed to dis before querying the log.
2586
func (s *Switch) FlushForwardingEvents() error {
3✔
2587
        // First, we'll obtain a copy of the current set of pending forwarding
3✔
2588
        // events.
3✔
2589
        s.fwdEventMtx.Lock()
3✔
2590

3✔
2591
        // If we won't have any forwarding events, then we can exit early.
3✔
2592
        if len(s.pendingFwdingEvents) == 0 {
6✔
2593
                s.fwdEventMtx.Unlock()
3✔
2594
                return nil
3✔
2595
        }
3✔
2596

2597
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
3✔
2598
        copy(events[:], s.pendingFwdingEvents[:])
3✔
2599

3✔
2600
        // With the copy obtained, we can now clear out the header pointer of
3✔
2601
        // the current slice. This way, we can re-use the underlying storage
3✔
2602
        // allocated for the slice.
3✔
2603
        s.pendingFwdingEvents = s.pendingFwdingEvents[:0]
3✔
2604
        s.fwdEventMtx.Unlock()
3✔
2605

3✔
2606
        // Finally, we'll write out the copied events to the persistent
3✔
2607
        // forwarding log.
3✔
2608
        return s.cfg.FwdingLog.AddForwardingEvents(events)
3✔
2609
}
2610

2611
// BestHeight returns the best height known to the switch.
2612
func (s *Switch) BestHeight() uint32 {
3✔
2613
        return atomic.LoadUint32(&s.bestHeight)
3✔
2614
}
3✔
2615

2616
// dustExceedsFeeThreshold takes in a ChannelLink, HTLC amount, and a boolean
2617
// to determine whether the default fee threshold has been exceeded. This
2618
// heuristic takes into account the trimmed-to-dust mechanism. The sum of the
2619
// commitment's dust with the mailbox's dust with the amount is checked against
2620
// the fee exposure threshold. If incoming is true, then the amount is not
2621
// included in the sum as it was already included in the commitment's dust. A
2622
// boolean is returned telling the caller whether the HTLC should be failed
2623
// back.
2624
func (s *Switch) dustExceedsFeeThreshold(link ChannelLink,
2625
        amount lnwire.MilliSatoshi, incoming bool) bool {
3✔
2626

3✔
2627
        // Retrieve the link's current commitment feerate and dustClosure.
3✔
2628
        feeRate := link.getFeeRate()
3✔
2629
        isDust := link.getDustClosure()
3✔
2630

3✔
2631
        // Evaluate if the HTLC is dust on either sides' commitment.
3✔
2632
        isLocalDust := isDust(
3✔
2633
                feeRate, incoming, lntypes.Local, amount.ToSatoshis(),
3✔
2634
        )
3✔
2635
        isRemoteDust := isDust(
3✔
2636
                feeRate, incoming, lntypes.Remote, amount.ToSatoshis(),
3✔
2637
        )
3✔
2638

3✔
2639
        if !(isLocalDust || isRemoteDust) {
6✔
2640
                // If the HTLC is not dust on either commitment, it's fine to
3✔
2641
                // forward.
3✔
2642
                return false
3✔
2643
        }
3✔
2644

2645
        // Fetch the dust sums currently in the mailbox for this link.
2646
        cid := link.ChanID()
3✔
2647
        sid := link.ShortChanID()
3✔
2648
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
3✔
2649
        localMailDust, remoteMailDust := mailbox.DustPackets()
3✔
2650

3✔
2651
        // If the htlc is dust on the local commitment, we'll obtain the dust
3✔
2652
        // sum for it.
3✔
2653
        if isLocalDust {
6✔
2654
                localSum := link.getDustSum(
3✔
2655
                        lntypes.Local, fn.None[chainfee.SatPerKWeight](),
3✔
2656
                )
3✔
2657
                localSum += localMailDust
3✔
2658

3✔
2659
                // Optionally include the HTLC amount only for outgoing
3✔
2660
                // HTLCs.
3✔
2661
                if !incoming {
6✔
2662
                        localSum += amount
3✔
2663
                }
3✔
2664

2665
                // Finally check against the defined fee threshold.
2666
                if localSum > s.cfg.MaxFeeExposure {
3✔
UNCOV
2667
                        return true
×
UNCOV
2668
                }
×
2669
        }
2670

2671
        // Also check if the htlc is dust on the remote commitment, if we've
2672
        // reached this point.
2673
        if isRemoteDust {
6✔
2674
                remoteSum := link.getDustSum(
3✔
2675
                        lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
3✔
2676
                )
3✔
2677
                remoteSum += remoteMailDust
3✔
2678

3✔
2679
                // Optionally include the HTLC amount only for outgoing
3✔
2680
                // HTLCs.
3✔
2681
                if !incoming {
6✔
2682
                        remoteSum += amount
3✔
2683
                }
3✔
2684

2685
                // Finally check against the defined fee threshold.
2686
                if remoteSum > s.cfg.MaxFeeExposure {
3✔
2687
                        return true
×
2688
                }
×
2689
        }
2690

2691
        // If we reached this point, this HTLC is fine to forward.
2692
        return false
3✔
2693
}
2694

2695
// failMailboxUpdate is passed to the mailbox orchestrator which in turn passes
2696
// it to individual mailboxes. It allows the mailboxes to construct a
2697
// FailureMessage when failing back HTLC's due to expiry and may include an
2698
// alias in the ShortChannelID field. The outgoingScid is the SCID originally
2699
// used in the onion. The mailboxScid is the SCID that the mailbox and link
2700
// use. The mailboxScid is only used in the non-alias case, so it is always
2701
// the confirmed SCID.
2702
func (s *Switch) failMailboxUpdate(outgoingScid,
2703
        mailboxScid lnwire.ShortChannelID) lnwire.FailureMessage {
2✔
2704

2✔
2705
        // Try to use the failAliasUpdate function in case this is a channel
2✔
2706
        // that uses aliases. If it returns nil, we'll fallback to the original
2✔
2707
        // pre-alias behavior.
2✔
2708
        update := s.failAliasUpdate(outgoingScid, false)
2✔
2709
        if update == nil {
4✔
2710
                // Execute the fallback behavior.
2✔
2711
                var err error
2✔
2712
                update, err = s.cfg.FetchLastChannelUpdate(mailboxScid)
2✔
2713
                if err != nil {
2✔
2714
                        return &lnwire.FailTemporaryNodeFailure{}
×
2715
                }
×
2716
        }
2717

2718
        return lnwire.NewTemporaryChannelFailure(update)
2✔
2719
}
2720

2721
// failAliasUpdate prepares a ChannelUpdate for a failed incoming or outgoing
2722
// HTLC on a channel where the option-scid-alias feature bit was negotiated. If
2723
// the associated channel is not one of these, this function will return nil
2724
// and the caller is expected to handle this properly. In this case, a return
2725
// to the original non-alias behavior is expected.
2726
func (s *Switch) failAliasUpdate(scid lnwire.ShortChannelID,
2727
        incoming bool) *lnwire.ChannelUpdate1 {
3✔
2728

3✔
2729
        // This function does not defer the unlocking because of the database
3✔
2730
        // lookups for ChannelUpdate.
3✔
2731
        s.indexMtx.RLock()
3✔
2732

3✔
2733
        if s.cfg.IsAlias(scid) {
6✔
2734
                // The alias SCID was used. In the incoming case this means
3✔
2735
                // the channel is zero-conf as the link sets the scid. In the
3✔
2736
                // outgoing case, the sender set the scid to use and may be
3✔
2737
                // either the alias or the confirmed one, if it exists.
3✔
2738
                realScid, ok := s.aliasToReal[scid]
3✔
2739
                if !ok {
3✔
2740
                        // The real, confirmed SCID does not exist yet. Find
×
2741
                        // the "base" SCID that the link uses via the
×
2742
                        // baseIndex. If we can't find it, return nil. This
×
2743
                        // means the channel is zero-conf.
×
2744
                        baseScid, ok := s.baseIndex[scid]
×
2745
                        s.indexMtx.RUnlock()
×
2746
                        if !ok {
×
2747
                                return nil
×
2748
                        }
×
2749

2750
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2751
                        if err != nil {
×
2752
                                return nil
×
2753
                        }
×
2754

2755
                        // Replace the baseScid with the passed-in alias.
2756
                        update.ShortChannelID = scid
×
2757
                        sig, err := s.cfg.SignAliasUpdate(update)
×
2758
                        if err != nil {
×
2759
                                return nil
×
2760
                        }
×
2761

2762
                        update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2763
                        if err != nil {
×
2764
                                return nil
×
2765
                        }
×
2766

2767
                        return update
×
2768
                }
2769

2770
                s.indexMtx.RUnlock()
3✔
2771

3✔
2772
                // Fetch the SCID via the confirmed SCID and replace it with
3✔
2773
                // the alias.
3✔
2774
                update, err := s.cfg.FetchLastChannelUpdate(realScid)
3✔
2775
                if err != nil {
6✔
2776
                        return nil
3✔
2777
                }
3✔
2778

2779
                // In the incoming case, we want to ensure that we don't leak
2780
                // the UTXO in case the channel is private. In the outgoing
2781
                // case, since the alias was used, we do the same thing.
2782
                update.ShortChannelID = scid
3✔
2783
                sig, err := s.cfg.SignAliasUpdate(update)
3✔
2784
                if err != nil {
3✔
2785
                        return nil
×
2786
                }
×
2787

2788
                update.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
2789
                if err != nil {
3✔
2790
                        return nil
×
2791
                }
×
2792

2793
                return update
3✔
2794
        }
2795

2796
        // If the confirmed SCID is not in baseIndex, this is not an
2797
        // option-scid-alias or zero-conf channel.
2798
        baseScid, ok := s.baseIndex[scid]
3✔
2799
        if !ok {
6✔
2800
                s.indexMtx.RUnlock()
3✔
2801
                return nil
3✔
2802
        }
3✔
2803

2804
        // Fetch the link so we can get an alias to use in the ShortChannelID
2805
        // of the ChannelUpdate.
UNCOV
2806
        link, ok := s.forwardingIndex[baseScid]
×
UNCOV
2807
        s.indexMtx.RUnlock()
×
UNCOV
2808
        if !ok {
×
2809
                // This should never happen, but if it does for some reason,
×
2810
                // fallback to the old behavior.
×
2811
                return nil
×
2812
        }
×
2813

UNCOV
2814
        aliases := link.getAliases()
×
UNCOV
2815
        if len(aliases) == 0 {
×
2816
                // This should never happen, but if it does, fallback.
×
2817
                return nil
×
2818
        }
×
2819

2820
        // Fetch the ChannelUpdate via the real, confirmed SCID.
UNCOV
2821
        update, err := s.cfg.FetchLastChannelUpdate(scid)
×
UNCOV
2822
        if err != nil {
×
2823
                return nil
×
2824
        }
×
2825

2826
        // The incoming case will replace the ShortChannelID in the retrieved
2827
        // ChannelUpdate with the alias to ensure no privacy leak occurs. This
2828
        // would happen if a private non-zero-conf option-scid-alias
2829
        // feature-bit channel leaked its UTXO here rather than supplying an
2830
        // alias. In the outgoing case, the confirmed SCID was actually used
2831
        // for forwarding in the onion, so no replacement is necessary as the
2832
        // sender knows the scid.
UNCOV
2833
        if incoming {
×
UNCOV
2834
                // We will replace and sign the update with the first alias.
×
UNCOV
2835
                // Since this happens on the incoming side, it's not actually
×
UNCOV
2836
                // possible to know what the sender used in the onion.
×
UNCOV
2837
                update.ShortChannelID = aliases[0]
×
UNCOV
2838
                sig, err := s.cfg.SignAliasUpdate(update)
×
UNCOV
2839
                if err != nil {
×
2840
                        return nil
×
2841
                }
×
2842

UNCOV
2843
                update.Signature, err = lnwire.NewSigFromSignature(sig)
×
UNCOV
2844
                if err != nil {
×
2845
                        return nil
×
2846
                }
×
2847
        }
2848

UNCOV
2849
        return update
×
2850
}
2851

2852
// AddAliasForLink instructs the Switch to update its in-memory maps to reflect
2853
// that a link has a new alias.
2854
func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
2855
        alias lnwire.ShortChannelID) error {
×
2856

×
2857
        // Fetch the link so that we can update the underlying channel's set of
×
2858
        // aliases.
×
2859
        s.indexMtx.RLock()
×
2860
        link, err := s.getLink(chanID)
×
2861
        s.indexMtx.RUnlock()
×
2862
        if err != nil {
×
2863
                return err
×
2864
        }
×
2865

2866
        // If the link is a channel where the option-scid-alias feature bit was
2867
        // not negotiated, we'll return an error.
2868
        if !link.negotiatedAliasFeature() {
×
2869
                return fmt.Errorf("attempted to update non-alias channel")
×
2870
        }
×
2871

2872
        linkScid := link.ShortChanID()
×
2873

×
2874
        // We'll update the maps so the Switch includes this alias in its
×
2875
        // forwarding decisions.
×
2876
        if link.isZeroConf() {
×
2877
                if link.zeroConfConfirmed() {
×
2878
                        // If the channel has confirmed on-chain, we'll
×
2879
                        // add this alias to the aliasToReal map.
×
2880
                        confirmedScid := link.confirmedScid()
×
2881

×
2882
                        s.aliasToReal[alias] = confirmedScid
×
2883
                }
×
2884

2885
                // Add this alias to the baseIndex mapping.
2886
                s.baseIndex[alias] = linkScid
×
2887
        } else if link.negotiatedAliasFeature() {
×
2888
                // The channel is confirmed, so we'll populate the aliasToReal
×
2889
                // and baseIndex maps.
×
2890
                s.aliasToReal[alias] = linkScid
×
2891
                s.baseIndex[alias] = linkScid
×
2892
        }
×
2893

2894
        return nil
×
2895
}
2896

2897
// handlePacketAdd handles forwarding an Add packet.
2898
func (s *Switch) handlePacketAdd(packet *htlcPacket,
2899
        htlc *lnwire.UpdateAddHTLC) error {
3✔
2900

3✔
2901
        // Check if the node is set to reject all onward HTLCs and also make
3✔
2902
        // sure that HTLC is not from the source node.
3✔
2903
        if s.cfg.RejectHTLC {
6✔
2904
                failure := NewDetailedLinkError(
3✔
2905
                        &lnwire.FailChannelDisabled{},
3✔
2906
                        OutgoingFailureForwardsDisabled,
3✔
2907
                )
3✔
2908

3✔
2909
                return s.failAddPacket(packet, failure)
3✔
2910
        }
3✔
2911

2912
        // Before we attempt to find a non-strict forwarding path for this
2913
        // htlc, check whether the htlc is being routed over the same incoming
2914
        // and outgoing channel. If our node does not allow forwards of this
2915
        // nature, we fail the htlc early. This check is in place to disallow
2916
        // inefficiently routed htlcs from locking up our balance. With
2917
        // channels where the option-scid-alias feature was negotiated, we also
2918
        // have to be sure that the IDs aren't the same since one or both could
2919
        // be an alias.
2920
        linkErr := s.checkCircularForward(
3✔
2921
                packet.incomingChanID, packet.outgoingChanID,
3✔
2922
                s.cfg.AllowCircularRoute, htlc.PaymentHash,
3✔
2923
        )
3✔
2924
        if linkErr != nil {
3✔
UNCOV
2925
                return s.failAddPacket(packet, linkErr)
×
UNCOV
2926
        }
×
2927

2928
        s.indexMtx.RLock()
3✔
2929
        targetLink, err := s.getLinkByMapping(packet)
3✔
2930
        if err != nil {
6✔
2931
                s.indexMtx.RUnlock()
3✔
2932

3✔
2933
                log.Debugf("unable to find link with "+
3✔
2934
                        "destination %v", packet.outgoingChanID)
3✔
2935

3✔
2936
                // If packet was forwarded from another channel link than we
3✔
2937
                // should notify this link that some error occurred.
3✔
2938
                linkError := NewLinkError(
3✔
2939
                        &lnwire.FailUnknownNextPeer{},
3✔
2940
                )
3✔
2941

3✔
2942
                return s.failAddPacket(packet, linkError)
3✔
2943
        }
3✔
2944
        targetPeerKey := targetLink.PeerPubKey()
3✔
2945
        interfaceLinks, _ := s.getLinks(targetPeerKey)
3✔
2946
        s.indexMtx.RUnlock()
3✔
2947

3✔
2948
        // We'll keep track of any HTLC failures during the link selection
3✔
2949
        // process. This way we can return the error for precise link that the
3✔
2950
        // sender selected, while optimistically trying all links to utilize
3✔
2951
        // our available bandwidth.
3✔
2952
        linkErrs := make(map[lnwire.ShortChannelID]*LinkError)
3✔
2953

3✔
2954
        // Find all destination channel links with appropriate bandwidth.
3✔
2955
        var destinations []ChannelLink
3✔
2956
        for _, link := range interfaceLinks {
6✔
2957
                var failure *LinkError
3✔
2958

3✔
2959
                // We'll skip any links that aren't yet eligible for
3✔
2960
                // forwarding.
3✔
2961
                if !link.EligibleToForward() {
3✔
UNCOV
2962
                        failure = NewDetailedLinkError(
×
UNCOV
2963
                                &lnwire.FailUnknownNextPeer{},
×
UNCOV
2964
                                OutgoingFailureLinkNotEligible,
×
UNCOV
2965
                        )
×
2966
                } else {
3✔
2967
                        // We'll ensure that the HTLC satisfies the current
3✔
2968
                        // forwarding conditions of this target link.
3✔
2969
                        currentHeight := atomic.LoadUint32(&s.bestHeight)
3✔
2970
                        failure = link.CheckHtlcForward(
3✔
2971
                                htlc.PaymentHash, packet.incomingAmount,
3✔
2972
                                packet.amount, packet.incomingTimeout,
3✔
2973
                                packet.outgoingTimeout, packet.inboundFee,
3✔
2974
                                currentHeight, packet.originalOutgoingChanID,
3✔
2975
                                htlc.CustomRecords,
3✔
2976
                        )
3✔
2977
                }
3✔
2978

2979
                // If this link can forward the htlc, add it to the set of
2980
                // destinations.
2981
                if failure == nil {
6✔
2982
                        destinations = append(destinations, link)
3✔
2983
                        continue
3✔
2984
                }
2985

2986
                linkErrs[link.ShortChanID()] = failure
3✔
2987
        }
2988

2989
        // If we had a forwarding failure due to the HTLC not satisfying the
2990
        // current policy, then we'll send back an error, but ensure we send
2991
        // back the error sourced at the *target* link.
2992
        if len(destinations) == 0 {
6✔
2993
                // At this point, some or all of the links rejected the HTLC so
3✔
2994
                // we couldn't forward it. So we'll try to look up the error
3✔
2995
                // that came from the source.
3✔
2996
                linkErr, ok := linkErrs[packet.outgoingChanID]
3✔
2997
                if !ok {
3✔
2998
                        // If we can't find the error of the source, then we'll
×
2999
                        // return an unknown next peer, though this should
×
3000
                        // never happen.
×
3001
                        linkErr = NewLinkError(
×
3002
                                &lnwire.FailUnknownNextPeer{},
×
3003
                        )
×
3004
                        log.Warnf("unable to find err source for "+
×
3005
                                "outgoing_link=%v, errors=%v",
×
3006
                                packet.outgoingChanID,
×
3007
                                lnutils.SpewLogClosure(linkErrs))
×
3008
                }
×
3009

3010
                log.Tracef("incoming HTLC(%x) violated "+
3✔
3011
                        "target outgoing link (id=%v) policy: %v",
3✔
3012
                        htlc.PaymentHash[:], packet.outgoingChanID,
3✔
3013
                        linkErr)
3✔
3014

3✔
3015
                return s.failAddPacket(packet, linkErr)
3✔
3016
        }
3017

3018
        // Choose a random link out of the set of links that can forward this
3019
        // htlc. The reason for randomization is to evenly distribute the htlc
3020
        // load without making assumptions about what the best channel is.
3021
        //nolint:gosec
3022
        destination := destinations[rand.Intn(len(destinations))]
3✔
3023

3✔
3024
        // Retrieve the incoming link by its ShortChannelID. Note that the
3✔
3025
        // incomingChanID is never set to hop.Source here.
3✔
3026
        s.indexMtx.RLock()
3✔
3027
        incomingLink, err := s.getLinkByShortID(packet.incomingChanID)
3✔
3028
        s.indexMtx.RUnlock()
3✔
3029
        if err != nil {
3✔
3030
                // If we couldn't find the incoming link, we can't evaluate the
×
3031
                // incoming's exposure to dust, so we just fail the HTLC back.
×
3032
                linkErr := NewLinkError(
×
3033
                        &lnwire.FailTemporaryChannelFailure{},
×
3034
                )
×
3035

×
3036
                return s.failAddPacket(packet, linkErr)
×
3037
        }
×
3038

3039
        // Evaluate whether this HTLC would increase our fee exposure over the
3040
        // threshold on the incoming link. If it does, fail it backwards.
3041
        if s.dustExceedsFeeThreshold(
3✔
3042
                incomingLink, packet.incomingAmount, true,
3✔
3043
        ) {
3✔
3044
                // The incoming dust exceeds the threshold, so we fail the add
×
3045
                // back.
×
3046
                linkErr := NewLinkError(
×
3047
                        &lnwire.FailTemporaryChannelFailure{},
×
3048
                )
×
3049

×
3050
                return s.failAddPacket(packet, linkErr)
×
3051
        }
×
3052

3053
        // Also evaluate whether this HTLC would increase our fee exposure over
3054
        // the threshold on the destination link. If it does, fail it back.
3055
        if s.dustExceedsFeeThreshold(
3✔
3056
                destination, packet.amount, false,
3✔
3057
        ) {
3✔
UNCOV
3058
                // The outgoing dust exceeds the threshold, so we fail the add
×
UNCOV
3059
                // back.
×
UNCOV
3060
                linkErr := NewLinkError(
×
UNCOV
3061
                        &lnwire.FailTemporaryChannelFailure{},
×
UNCOV
3062
                )
×
UNCOV
3063

×
UNCOV
3064
                return s.failAddPacket(packet, linkErr)
×
UNCOV
3065
        }
×
3066

3067
        // Send the packet to the destination channel link which manages the
3068
        // channel.
3069
        packet.outgoingChanID = destination.ShortChanID()
3✔
3070

3✔
3071
        return destination.handleSwitchPacket(packet)
3✔
3072
}
3073

3074
// handlePacketSettle handles forwarding a settle packet.
3075
func (s *Switch) handlePacketSettle(packet *htlcPacket) error {
3✔
3076
        // If the source of this packet has not been set, use the circuit map
3✔
3077
        // to lookup the origin.
3✔
3078
        circuit, err := s.closeCircuit(packet)
3✔
3079

3✔
3080
        // If the circuit is in the process of closing, we will return a nil as
3✔
3081
        // there's another packet handling undergoing.
3✔
3082
        if errors.Is(err, ErrCircuitClosing) {
6✔
3083
                log.Debugf("Circuit is closing for packet=%v", packet)
3✔
3084
                return nil
3✔
3085
        }
3✔
3086

3087
        // Exit early if there's another error.
3088
        if err != nil {
3✔
3089
                return err
×
3090
        }
×
3091

3092
        // closeCircuit returns a nil circuit when a settle packet returns an
3093
        // ErrUnknownCircuit error upon the inner call to CloseCircuit.
3094
        //
3095
        // NOTE: We can only get a nil circuit when it has already been deleted
3096
        // and when `UpdateFulfillHTLC` is received. After which `RevokeAndAck`
3097
        // is received, which invokes `processRemoteSettleFails` in its link.
3098
        if circuit == nil {
6✔
3099
                log.Debugf("Circuit already closed for packet=%v", packet)
3✔
3100
                return nil
3✔
3101
        }
3✔
3102

3103
        localHTLC := packet.incomingChanID == hop.Source
3✔
3104

3✔
3105
        // If this is a locally initiated HTLC, we need to handle the packet by
3✔
3106
        // storing the network result.
3✔
3107
        //
3✔
3108
        // A blank IncomingChanID in a circuit indicates that it is a pending
3✔
3109
        // user-initiated payment.
3✔
3110
        //
3✔
3111
        // NOTE: `closeCircuit` modifies the state of `packet`.
3✔
3112
        if localHTLC {
6✔
3113
                // TODO(yy): remove the goroutine and send back the error here.
3✔
3114
                s.wg.Add(1)
3✔
3115
                go s.handleLocalResponse(packet)
3✔
3116

3✔
3117
                // If this is a locally initiated HTLC, there's no need to
3✔
3118
                // forward it so we exit.
3✔
3119
                return nil
3✔
3120
        }
3✔
3121

3122
        // If this is an HTLC settle, and it wasn't from a locally initiated
3123
        // HTLC, then we'll log a forwarding event so we can flush it to disk
3124
        // later.
3125
        if circuit.Outgoing != nil {
6✔
3126
                log.Infof("Forwarded HTLC(%x) of %v (fee: %v) "+
3✔
3127
                        "from IncomingChanID(%v) to OutgoingChanID(%v)",
3✔
3128
                        circuit.PaymentHash[:], circuit.OutgoingAmount,
3✔
3129
                        circuit.IncomingAmount-circuit.OutgoingAmount,
3✔
3130
                        circuit.Incoming.ChanID, circuit.Outgoing.ChanID)
3✔
3131

3✔
3132
                s.fwdEventMtx.Lock()
3✔
3133
                s.pendingFwdingEvents = append(
3✔
3134
                        s.pendingFwdingEvents,
3✔
3135
                        channeldb.ForwardingEvent{
3✔
3136
                                Timestamp:      time.Now(),
3✔
3137
                                IncomingChanID: circuit.Incoming.ChanID,
3✔
3138
                                OutgoingChanID: circuit.Outgoing.ChanID,
3✔
3139
                                AmtIn:          circuit.IncomingAmount,
3✔
3140
                                AmtOut:         circuit.OutgoingAmount,
3✔
3141
                                IncomingHtlcID: fn.Some(
3✔
3142
                                        circuit.Incoming.HtlcID,
3✔
3143
                                ),
3✔
3144
                                OutgoingHtlcID: fn.Some(
3✔
3145
                                        circuit.Outgoing.HtlcID,
3✔
3146
                                ),
3✔
3147
                        },
3✔
3148
                )
3✔
3149
                s.fwdEventMtx.Unlock()
3✔
3150
        }
3✔
3151

3152
        // Deliver this packet.
3153
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3154
}
3155

3156
// handlePacketFail handles forwarding a fail packet.
3157
func (s *Switch) handlePacketFail(packet *htlcPacket,
3158
        htlc *lnwire.UpdateFailHTLC) error {
3✔
3159

3✔
3160
        // If the source of this packet has not been set, use the circuit map
3✔
3161
        // to lookup the origin.
3✔
3162
        circuit, err := s.closeCircuit(packet)
3✔
3163
        if err != nil {
3✔
3164
                return err
×
3165
        }
×
3166

3167
        // If this is a locally initiated HTLC, we need to handle the packet by
3168
        // storing the network result.
3169
        //
3170
        // A blank IncomingChanID in a circuit indicates that it is a pending
3171
        // user-initiated payment.
3172
        //
3173
        // NOTE: `closeCircuit` modifies the state of `packet`.
3174
        if packet.incomingChanID == hop.Source {
6✔
3175
                // TODO(yy): remove the goroutine and send back the error here.
3✔
3176
                s.wg.Add(1)
3✔
3177
                go s.handleLocalResponse(packet)
3✔
3178

3✔
3179
                // If this is a locally initiated HTLC, there's no need to
3✔
3180
                // forward it so we exit.
3✔
3181
                return nil
3✔
3182
        }
3✔
3183

3184
        // Exit early if this hasSource is true. This flag is only set via
3185
        // mailbox's `FailAdd`. This method has two callsites,
3186
        // - the packet has timed out after `MailboxDeliveryTimeout`, defaults
3187
        //   to 1 min.
3188
        // - the HTLC fails the validation in `channel.AddHTLC`.
3189
        // In either case, the `Reason` field is populated. Thus there's no
3190
        // need to proceed and extract the failure reason below.
3191
        if packet.hasSource {
3✔
UNCOV
3192
                // Deliver this packet.
×
UNCOV
3193
                return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
×
UNCOV
3194
        }
×
3195

3196
        // HTLC resolutions and messages restored from disk don't have the
3197
        // obfuscator set from the original htlc add packet - set it here for
3198
        // use in blinded errors.
3199
        packet.obfuscator = circuit.ErrorEncrypter
3✔
3200

3✔
3201
        switch {
3✔
3202
        // No message to encrypt, locally sourced payment.
3203
        case circuit.ErrorEncrypter == nil:
×
3204
                // TODO(yy) further check this case as we shouldn't end up here
3205
                // as `isLocal` is already false.
3206

3207
        // If this is a resolution message, then we'll need to encrypt it as
3208
        // it's actually internally sourced.
3209
        case packet.isResolution:
3✔
3210
                var err error
3✔
3211
                // TODO(roasbeef): don't need to pass actually?
3✔
3212
                failure := &lnwire.FailPermanentChannelFailure{}
3✔
3213
                htlc.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
3✔
3214
                        failure,
3✔
3215
                )
3✔
3216
                if err != nil {
3✔
3217
                        err = fmt.Errorf("unable to obfuscate error: %w", err)
×
3218
                        log.Error(err)
×
3219
                }
×
3220

3221
        // Alternatively, if the remote party sends us an
3222
        // UpdateFailMalformedHTLC, then we'll need to convert this into a
3223
        // proper well formatted onion error as there's no HMAC currently.
3224
        case packet.convertedError:
3✔
3225
                log.Infof("Converting malformed HTLC error for circuit for "+
3✔
3226
                        "Circuit(%x: (%s, %d) <-> (%s, %d))",
3✔
3227
                        packet.circuit.PaymentHash,
3✔
3228
                        packet.incomingChanID, packet.incomingHTLCID,
3✔
3229
                        packet.outgoingChanID, packet.outgoingHTLCID)
3✔
3230

3✔
3231
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
3✔
3232
                        htlc.Reason,
3✔
3233
                )
3✔
3234

3235
        default:
3✔
3236
                // Otherwise, it's a forwarded error, so we'll perform a
3✔
3237
                // wrapper encryption as normal.
3✔
3238
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
3✔
3239
                        htlc.Reason,
3✔
3240
                )
3✔
3241
        }
3242

3243
        // Deliver this packet.
3244
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3245
}
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