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

lightningnetwork / lnd / 13980275562

20 Mar 2025 10:06PM UTC coverage: 58.6% (-10.2%) from 68.789%
13980275562

Pull #9623

github

web-flow
Merge b9b960345 into 09b674508
Pull Request #9623: Size msg test msg

0 of 1518 new or added lines in 42 files covered. (0.0%)

26603 existing lines in 443 files now uncovered.

96807 of 165200 relevant lines covered (58.6%)

1.82 hits per line

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

74.4
/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/davecgh/go-spew/spew"
17
        "github.com/lightningnetwork/lnd/chainntnfs"
18
        "github.com/lightningnetwork/lnd/channeldb"
19
        "github.com/lightningnetwork/lnd/clock"
20
        "github.com/lightningnetwork/lnd/contractcourt"
21
        "github.com/lightningnetwork/lnd/fn/v2"
22
        "github.com/lightningnetwork/lnd/graph/db/models"
23
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
24
        "github.com/lightningnetwork/lnd/kvdb"
25
        "github.com/lightningnetwork/lnd/lntypes"
26
        "github.com/lightningnetwork/lnd/lnutils"
27
        "github.com/lightningnetwork/lnd/lnwallet"
28
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
29
        "github.com/lightningnetwork/lnd/lnwire"
30
        "github.com/lightningnetwork/lnd/ticker"
31
)
32

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
        errChan chan error
412
}
413

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

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

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

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

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

451
        return false, nil
3✔
452
}
453

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

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

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

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

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

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

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

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

533
        return resultChan, nil
3✔
534
}
535

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

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

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

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

3✔
581
                return linkErr
3✔
582
        }
3✔
583

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

×
UNCOV
604
                return errFeeExposureExceeded
×
UNCOV
605
        }
×
606

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

823
        return nil
3✔
824
}
825

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

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

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

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

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

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

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

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

899
                // The base SCID was found, so we'll use that to fetch the
900
                // link.
901
                link, err = s.getLinkByShortID(baseScid)
3✔
902
                if err != nil {
3✔
903
                        log.Errorf("Link %v not found", baseScid)
×
904
                        return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
×
905
                }
×
906
        }
907

908
        if !link.EligibleToForward() {
3✔
UNCOV
909
                log.Errorf("Link %v is not available to forward",
×
UNCOV
910
                        pkt.outgoingChanID)
×
UNCOV
911

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

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

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

3✔
949
        attemptID := pkt.incomingHTLCID
3✔
950

3✔
951
        // The error reason will be unencypted in case this a local
3✔
952
        // failure or a converted error.
3✔
953
        unencrypted := pkt.localFailure || pkt.convertedError
3✔
954
        n := &networkResult{
3✔
955
                msg:          pkt.htlc,
3✔
956
                unencrypted:  unencrypted,
3✔
957
                isResolution: pkt.isResolution,
3✔
958
        }
3✔
959

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

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

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

996
        // Finally, notify on the htlc failure or success that has been handled.
997
        key := newHtlcKey(pkt)
3✔
998
        eventType := getEventType(pkt)
3✔
999

3✔
1000
        switch htlc := pkt.htlc.(type) {
3✔
1001
        case *lnwire.UpdateFulfillHTLC:
3✔
1002
                s.cfg.HtlcNotifier.NotifySettleEvent(key, htlc.PaymentPreimage,
3✔
1003
                        eventType)
3✔
1004

1005
        case *lnwire.UpdateFailHTLC:
3✔
1006
                s.cfg.HtlcNotifier.NotifyForwardingFailEvent(key, eventType)
3✔
1007
        }
1008
}
1009

1010
// extractResult uses the given deobfuscator to extract the payment result from
1011
// the given network message.
1012
func (s *Switch) extractResult(deobfuscator ErrorDecrypter, n *networkResult,
1013
        attemptID uint64, paymentHash lntypes.Hash) (*PaymentResult, error) {
3✔
1014

3✔
1015
        switch htlc := n.msg.(type) {
3✔
1016

1017
        // We've received a settle update which means we can finalize the user
1018
        // payment and return successful response.
1019
        case *lnwire.UpdateFulfillHTLC:
3✔
1020
                return &PaymentResult{
3✔
1021
                        Preimage: htlc.PaymentPreimage,
3✔
1022
                }, nil
3✔
1023

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

3✔
1034
                return &PaymentResult{
3✔
1035
                        Error: paymentErr,
3✔
1036
                }, nil
3✔
1037

1038
        default:
×
1039
                return nil, fmt.Errorf("received unknown response type: %T",
×
1040
                        htlc)
×
1041
        }
1042
}
1043

1044
// parseFailedPayment determines the appropriate failure message to return to
1045
// a user initiated payment. The three cases handled are:
1046
//  1. An unencrypted failure, which should already plaintext.
1047
//  2. A resolution from the chain arbitrator, which possibly has no failure
1048
//     reason attached.
1049
//  3. A failure from the remote party, which will need to be decrypted using
1050
//     the payment deobfuscator.
1051
func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
1052
        attemptID uint64, paymentHash lntypes.Hash, unencrypted,
1053
        isResolution bool, htlc *lnwire.UpdateFailHTLC) error {
3✔
1054

3✔
1055
        switch {
3✔
1056

1057
        // The payment never cleared the link, so we don't need to
1058
        // decrypt the error, simply decode it them report back to the
1059
        // user.
1060
        case unencrypted:
3✔
1061
                r := bytes.NewReader(htlc.Reason)
3✔
1062
                failureMsg, err := lnwire.DecodeFailure(r, 0)
3✔
1063
                if err != nil {
3✔
1064
                        // If we could not decode the failure reason, return a link
×
1065
                        // error indicating that we failed to decode the onion.
×
1066
                        linkError := NewDetailedLinkError(
×
1067
                                // As this didn't even clear the link, we don't
×
1068
                                // need to apply an update here since it goes
×
1069
                                // directly to the router.
×
1070
                                lnwire.NewTemporaryChannelFailure(nil),
×
1071
                                OutgoingFailureDecodeError,
×
1072
                        )
×
1073

×
1074
                        log.Errorf("%v: (hash=%v, pid=%d): %v",
×
1075
                                linkError.FailureDetail.FailureString(),
×
1076
                                paymentHash, attemptID, err)
×
1077

×
1078
                        return linkError
×
1079
                }
×
1080

1081
                // If we successfully decoded the failure reason, return it.
1082
                return NewLinkError(failureMsg)
3✔
1083

1084
        // A payment had to be timed out on chain before it got past
1085
        // the first hop. In this case, we'll report a permanent
1086
        // channel failure as this means us, or the remote party had to
1087
        // go on chain.
1088
        case isResolution && htlc.Reason == nil:
3✔
1089
                linkError := NewDetailedLinkError(
3✔
1090
                        &lnwire.FailPermanentChannelFailure{},
3✔
1091
                        OutgoingFailureOnChainTimeout,
3✔
1092
                )
3✔
1093

3✔
1094
                log.Infof("%v: hash=%v, pid=%d",
3✔
1095
                        linkError.FailureDetail.FailureString(),
3✔
1096
                        paymentHash, attemptID)
3✔
1097

3✔
1098
                return linkError
3✔
1099

1100
        // A regular multi-hop payment error that we'll need to
1101
        // decrypt.
1102
        default:
3✔
1103
                // We'll attempt to fully decrypt the onion encrypted
3✔
1104
                // error. If we're unable to then we'll bail early.
3✔
1105
                failure, err := deobfuscator.DecryptError(htlc.Reason)
3✔
1106
                if err != nil {
3✔
UNCOV
1107
                        log.Errorf("unable to de-obfuscate onion failure "+
×
UNCOV
1108
                                "(hash=%v, pid=%d): %v",
×
UNCOV
1109
                                paymentHash, attemptID, err)
×
UNCOV
1110

×
UNCOV
1111
                        return ErrUnreadableFailureMessage
×
UNCOV
1112
                }
×
1113

1114
                return failure
3✔
1115
        }
1116
}
1117

1118
// handlePacketForward is used in cases when we need forward the htlc update
1119
// from one channel link to another and be able to propagate the settle/fail
1120
// updates back. This behaviour is achieved by creation of payment circuits.
1121
func (s *Switch) handlePacketForward(packet *htlcPacket) error {
3✔
1122
        switch htlc := packet.htlc.(type) {
3✔
1123
        // Channel link forwarded us a new htlc, therefore we initiate the
1124
        // payment circuit within our internal state so we can properly forward
1125
        // the ultimate settle message back latter.
1126
        case *lnwire.UpdateAddHTLC:
3✔
1127
                return s.handlePacketAdd(packet, htlc)
3✔
1128

1129
        case *lnwire.UpdateFulfillHTLC:
3✔
1130
                return s.handlePacketSettle(packet)
3✔
1131

1132
        // Channel link forwarded us an update_fail_htlc message.
1133
        //
1134
        // NOTE: when the channel link receives an update_fail_malformed_htlc
1135
        // from upstream, it will convert the message into update_fail_htlc and
1136
        // forward it. Thus there's no need to catch `UpdateFailMalformedHTLC`
1137
        // here.
1138
        case *lnwire.UpdateFailHTLC:
3✔
1139
                return s.handlePacketFail(packet, htlc)
3✔
1140

1141
        default:
×
1142
                return fmt.Errorf("wrong update type: %T", htlc)
×
1143
        }
1144
}
1145

1146
// checkCircularForward checks whether a forward is circular (arrives and
1147
// departs on the same link) and returns a link error if the switch is
1148
// configured to disallow this behaviour.
1149
func (s *Switch) checkCircularForward(incoming, outgoing lnwire.ShortChannelID,
1150
        allowCircular bool, paymentHash lntypes.Hash) *LinkError {
3✔
1151

3✔
1152
        // If they are equal, we can skip the alias mapping checks.
3✔
1153
        if incoming == outgoing {
3✔
UNCOV
1154
                // The switch may be configured to allow circular routes, so
×
UNCOV
1155
                // just log and return nil.
×
UNCOV
1156
                if allowCircular {
×
UNCOV
1157
                        log.Debugf("allowing circular route over link: %v "+
×
UNCOV
1158
                                "(payment hash: %x)", incoming, paymentHash)
×
UNCOV
1159
                        return nil
×
UNCOV
1160
                }
×
1161

1162
                // Otherwise, we'll return a temporary channel failure.
UNCOV
1163
                return NewDetailedLinkError(
×
UNCOV
1164
                        lnwire.NewTemporaryChannelFailure(nil),
×
UNCOV
1165
                        OutgoingFailureCircularRoute,
×
UNCOV
1166
                )
×
1167
        }
1168

1169
        // We'll fetch the "base" SCID from the baseIndex for the incoming and
1170
        // outgoing SCIDs. If either one does not have a base SCID, then the
1171
        // two channels are not equal since one will be a channel that does not
1172
        // need a mapping and SCID equality was checked above. If the "base"
1173
        // SCIDs are equal, then this is a circular route. Otherwise, it isn't.
1174
        s.indexMtx.RLock()
3✔
1175
        incomingBaseScid, ok := s.baseIndex[incoming]
3✔
1176
        if !ok {
6✔
1177
                // This channel does not use baseIndex, bail out.
3✔
1178
                s.indexMtx.RUnlock()
3✔
1179
                return nil
3✔
1180
        }
3✔
1181

1182
        outgoingBaseScid, ok := s.baseIndex[outgoing]
3✔
1183
        if !ok {
6✔
1184
                // This channel does not use baseIndex, bail out.
3✔
1185
                s.indexMtx.RUnlock()
3✔
1186
                return nil
3✔
1187
        }
3✔
1188
        s.indexMtx.RUnlock()
3✔
1189

3✔
1190
        // Check base SCID equality.
3✔
1191
        if incomingBaseScid != outgoingBaseScid {
6✔
1192
                // The base SCIDs are not equal so these are not the same
3✔
1193
                // channel.
3✔
1194
                return nil
3✔
1195
        }
3✔
1196

1197
        // If the incoming and outgoing link are equal, the htlc is part of a
1198
        // circular route which may be used to lock up our liquidity. If the
1199
        // switch is configured to allow circular routes, log that we are
1200
        // allowing the route then return nil.
UNCOV
1201
        if allowCircular {
×
UNCOV
1202
                log.Debugf("allowing circular route over link: %v "+
×
UNCOV
1203
                        "(payment hash: %x)", incoming, paymentHash)
×
UNCOV
1204
                return nil
×
UNCOV
1205
        }
×
1206

1207
        // If our node disallows circular routes, return a temporary channel
1208
        // failure. There is nothing wrong with the policy used by the remote
1209
        // node, so we do not include a channel update.
UNCOV
1210
        return NewDetailedLinkError(
×
UNCOV
1211
                lnwire.NewTemporaryChannelFailure(nil),
×
UNCOV
1212
                OutgoingFailureCircularRoute,
×
UNCOV
1213
        )
×
1214
}
1215

1216
// failAddPacket encrypts a fail packet back to an add packet's source.
1217
// The ciphertext will be derived from the failure message proivded by context.
1218
// This method returns the failErr if all other steps complete successfully.
1219
func (s *Switch) failAddPacket(packet *htlcPacket, failure *LinkError) error {
3✔
1220
        // Encrypt the failure so that the sender will be able to read the error
3✔
1221
        // message. Since we failed this packet, we use EncryptFirstHop to
3✔
1222
        // obfuscate the failure for their eyes only.
3✔
1223
        reason, err := packet.obfuscator.EncryptFirstHop(failure.WireMessage())
3✔
1224
        if err != nil {
3✔
1225
                err := fmt.Errorf("unable to obfuscate "+
×
1226
                        "error: %v", err)
×
1227
                log.Error(err)
×
1228
                return err
×
1229
        }
×
1230

1231
        log.Error(failure.Error())
3✔
1232

3✔
1233
        // Create a failure packet for this htlc. The full set of
3✔
1234
        // information about the htlc failure is included so that they can
3✔
1235
        // be included in link failure notifications.
3✔
1236
        failPkt := &htlcPacket{
3✔
1237
                sourceRef:       packet.sourceRef,
3✔
1238
                incomingChanID:  packet.incomingChanID,
3✔
1239
                incomingHTLCID:  packet.incomingHTLCID,
3✔
1240
                outgoingChanID:  packet.outgoingChanID,
3✔
1241
                outgoingHTLCID:  packet.outgoingHTLCID,
3✔
1242
                incomingAmount:  packet.incomingAmount,
3✔
1243
                amount:          packet.amount,
3✔
1244
                incomingTimeout: packet.incomingTimeout,
3✔
1245
                outgoingTimeout: packet.outgoingTimeout,
3✔
1246
                circuit:         packet.circuit,
3✔
1247
                obfuscator:      packet.obfuscator,
3✔
1248
                linkFailure:     failure,
3✔
1249
                htlc: &lnwire.UpdateFailHTLC{
3✔
1250
                        Reason: reason,
3✔
1251
                },
3✔
1252
        }
3✔
1253

3✔
1254
        // Route a fail packet back to the source link.
3✔
1255
        err = s.mailOrchestrator.Deliver(failPkt.incomingChanID, failPkt)
3✔
1256
        if err != nil {
3✔
1257
                err = fmt.Errorf("source chanid=%v unable to "+
×
1258
                        "handle switch packet: %v",
×
1259
                        packet.incomingChanID, err)
×
1260
                log.Error(err)
×
1261
                return err
×
1262
        }
×
1263

1264
        return failure
3✔
1265
}
1266

1267
// closeCircuit accepts a settle or fail htlc and the associated htlc packet and
1268
// attempts to determine the source that forwarded this htlc. This method will
1269
// set the incoming chan and htlc ID of the given packet if the source was
1270
// found, and will properly [re]encrypt any failure messages.
1271
func (s *Switch) closeCircuit(pkt *htlcPacket) (*PaymentCircuit, error) {
3✔
1272
        // If the packet has its source, that means it was failed locally by
3✔
1273
        // the outgoing link. We fail it here to make sure only one response
3✔
1274
        // makes it through the switch.
3✔
1275
        if pkt.hasSource {
6✔
1276
                circuit, err := s.circuits.FailCircuit(pkt.inKey())
3✔
1277
                switch err {
3✔
1278

1279
                // Circuit successfully closed.
1280
                case nil:
3✔
1281
                        return circuit, nil
3✔
1282

1283
                // Circuit was previously closed, but has not been deleted.
1284
                // We'll just drop this response until the circuit has been
1285
                // fully removed.
1286
                case ErrCircuitClosing:
×
1287
                        return nil, err
×
1288

1289
                // Failed to close circuit because it does not exist. This is
1290
                // likely because the circuit was already successfully closed.
1291
                // Since this packet failed locally, there is no forwarding
1292
                // package entry to acknowledge.
1293
                case ErrUnknownCircuit:
×
1294
                        return nil, err
×
1295

1296
                // Unexpected error.
1297
                default:
×
1298
                        return nil, err
×
1299
                }
1300
        }
1301

1302
        // Otherwise, this is packet was received from the remote party.  Use
1303
        // circuit map to find the incoming link to receive the settle/fail.
1304
        circuit, err := s.circuits.CloseCircuit(pkt.outKey())
3✔
1305
        switch err {
3✔
1306

1307
        // Open circuit successfully closed.
1308
        case nil:
3✔
1309
                pkt.incomingChanID = circuit.Incoming.ChanID
3✔
1310
                pkt.incomingHTLCID = circuit.Incoming.HtlcID
3✔
1311
                pkt.circuit = circuit
3✔
1312
                pkt.sourceRef = &circuit.AddRef
3✔
1313

3✔
1314
                pktType := "SETTLE"
3✔
1315
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
6✔
1316
                        pktType = "FAIL"
3✔
1317
                }
3✔
1318

1319
                log.Debugf("Closed completed %s circuit for %x: "+
3✔
1320
                        "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
3✔
1321
                        pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1322
                        pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1323

3✔
1324
                return circuit, nil
3✔
1325

1326
        // Circuit was previously closed, but has not been deleted. We'll just
1327
        // drop this response until the circuit has been removed.
1328
        case ErrCircuitClosing:
3✔
1329
                return nil, err
3✔
1330

1331
        // Failed to close circuit because it does not exist. This is likely
1332
        // because the circuit was already successfully closed.
1333
        case ErrUnknownCircuit:
3✔
1334
                if pkt.destRef != nil {
6✔
1335
                        // Add this SettleFailRef to the set of pending settle/fail entries
3✔
1336
                        // awaiting acknowledgement.
3✔
1337
                        s.pendingSettleFails = append(s.pendingSettleFails, *pkt.destRef)
3✔
1338
                }
3✔
1339

1340
                // If this is a settle, we will not log an error message as settles
1341
                // are expected to hit the ErrUnknownCircuit case. The only way fails
1342
                // can hit this case if the link restarts after having just sent a fail
1343
                // to the switch.
1344
                _, isSettle := pkt.htlc.(*lnwire.UpdateFulfillHTLC)
3✔
1345
                if !isSettle {
3✔
1346
                        err := fmt.Errorf("unable to find target channel "+
×
1347
                                "for HTLC fail: channel ID = %s, "+
×
1348
                                "HTLC ID = %d", pkt.outgoingChanID,
×
1349
                                pkt.outgoingHTLCID)
×
1350
                        log.Error(err)
×
1351

×
1352
                        return nil, err
×
1353
                }
×
1354

1355
                return nil, nil
3✔
1356

1357
        // Unexpected error.
1358
        default:
×
1359
                return nil, err
×
1360
        }
1361
}
1362

1363
// ackSettleFail is used by the switch to ACK any settle/fail entries in the
1364
// forwarding package of the outgoing link for a payment circuit. We do this if
1365
// we're the originator of the payment, so the link stops attempting to
1366
// re-broadcast.
1367
func (s *Switch) ackSettleFail(settleFailRefs ...channeldb.SettleFailRef) error {
3✔
1368
        return kvdb.Batch(s.cfg.DB, func(tx kvdb.RwTx) error {
6✔
1369
                return s.cfg.SwitchPackager.AckSettleFails(tx, settleFailRefs...)
3✔
1370
        })
3✔
1371
}
1372

1373
// teardownCircuit removes a pending or open circuit from the switch's circuit
1374
// map and prints useful logging statements regarding the outcome.
1375
func (s *Switch) teardownCircuit(pkt *htlcPacket) error {
3✔
1376
        var pktType string
3✔
1377
        switch htlc := pkt.htlc.(type) {
3✔
1378
        case *lnwire.UpdateFulfillHTLC:
3✔
1379
                pktType = "SETTLE"
3✔
1380
        case *lnwire.UpdateFailHTLC:
3✔
1381
                pktType = "FAIL"
3✔
1382
        default:
×
1383
                return fmt.Errorf("cannot tear down packet of type: %T", htlc)
×
1384
        }
1385

1386
        var paymentHash lntypes.Hash
3✔
1387

3✔
1388
        // Perform a defensive check to make sure we don't try to access a nil
3✔
1389
        // circuit.
3✔
1390
        circuit := pkt.circuit
3✔
1391
        if circuit != nil {
6✔
1392
                copy(paymentHash[:], circuit.PaymentHash[:])
3✔
1393
        }
3✔
1394

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

3✔
1398
        err := s.circuits.DeleteCircuits(pkt.inKey())
3✔
1399
        if err != nil {
3✔
1400
                log.Warnf("Failed to tear down circuit (%s, %d) <-> (%s, %d) "+
×
1401
                        "with payment_hash=%v using %s pkt", pkt.incomingChanID,
×
1402
                        pkt.incomingHTLCID, pkt.outgoingChanID,
×
1403
                        pkt.outgoingHTLCID, pkt.circuit.PaymentHash, pktType)
×
1404

×
1405
                return err
×
1406
        }
×
1407

1408
        log.Debugf("Closed %s circuit for %v: (%s, %d) <-> (%s, %d)", pktType,
3✔
1409
                paymentHash, pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1410
                pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1411

3✔
1412
        return nil
3✔
1413
}
1414

1415
// CloseLink creates and sends the close channel command to the target link
1416
// directing the specified closure type. If the closure type is CloseRegular,
1417
// targetFeePerKw parameter should be the ideal fee-per-kw that will be used as
1418
// a starting point for close negotiation. The deliveryScript parameter is an
1419
// optional parameter which sets a user specified script to close out to.
1420
func (s *Switch) CloseLink(ctx context.Context, chanPoint *wire.OutPoint,
1421
        closeType contractcourt.ChannelCloseType,
1422
        targetFeePerKw, maxFee chainfee.SatPerKWeight,
1423
        deliveryScript lnwire.DeliveryAddress) (chan interface{}, chan error) {
3✔
1424

3✔
1425
        // TODO(roasbeef) abstract out the close updates.
3✔
1426
        updateChan := make(chan interface{}, 2)
3✔
1427
        errChan := make(chan error, 1)
3✔
1428

3✔
1429
        command := &ChanClose{
3✔
1430
                CloseType:      closeType,
3✔
1431
                ChanPoint:      chanPoint,
3✔
1432
                Updates:        updateChan,
3✔
1433
                TargetFeePerKw: targetFeePerKw,
3✔
1434
                DeliveryScript: deliveryScript,
3✔
1435
                Err:            errChan,
3✔
1436
                MaxFee:         maxFee,
3✔
1437
                Ctx:            ctx,
3✔
1438
        }
3✔
1439

3✔
1440
        select {
3✔
1441
        case s.chanCloseRequests <- command:
3✔
1442
                return updateChan, errChan
3✔
1443

1444
        case <-s.quit:
×
1445
                errChan <- ErrSwitchExiting
×
1446
                close(updateChan)
×
1447
                return updateChan, errChan
×
1448
        }
1449
}
1450

1451
// htlcForwarder is responsible for optimally forwarding (and possibly
1452
// fragmenting) incoming/outgoing HTLCs amongst all active interfaces and their
1453
// links. The duties of the forwarder are similar to that of a network switch,
1454
// in that it facilitates multi-hop payments by acting as a central messaging
1455
// bus. The switch communicates will active links to create, manage, and tear
1456
// down active onion routed payments. Each active channel is modeled as
1457
// networked device with metadata such as the available payment bandwidth, and
1458
// total link capacity.
1459
//
1460
// NOTE: This MUST be run as a goroutine.
1461
func (s *Switch) htlcForwarder() {
3✔
1462
        defer s.wg.Done()
3✔
1463

3✔
1464
        defer func() {
6✔
1465
                s.blockEpochStream.Cancel()
3✔
1466

3✔
1467
                // Remove all links once we've been signalled for shutdown.
3✔
1468
                var linksToStop []ChannelLink
3✔
1469
                s.indexMtx.Lock()
3✔
1470
                for _, link := range s.linkIndex {
6✔
1471
                        activeLink := s.removeLink(link.ChanID())
3✔
1472
                        if activeLink == nil {
3✔
1473
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1474
                                        "on stop", link.ChanID())
×
1475
                                continue
×
1476
                        }
1477
                        linksToStop = append(linksToStop, activeLink)
3✔
1478
                }
1479
                for _, link := range s.pendingLinkIndex {
6✔
1480
                        pendingLink := s.removeLink(link.ChanID())
3✔
1481
                        if pendingLink == nil {
3✔
1482
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1483
                                        "on stop", link.ChanID())
×
1484
                                continue
×
1485
                        }
1486
                        linksToStop = append(linksToStop, pendingLink)
3✔
1487
                }
1488
                s.indexMtx.Unlock()
3✔
1489

3✔
1490
                // Now that all pending and live links have been removed from
3✔
1491
                // the forwarding indexes, stop each one before shutting down.
3✔
1492
                // We'll shut them down in parallel to make exiting as fast as
3✔
1493
                // possible.
3✔
1494
                var wg sync.WaitGroup
3✔
1495
                for _, link := range linksToStop {
6✔
1496
                        wg.Add(1)
3✔
1497
                        go func(l ChannelLink) {
6✔
1498
                                defer wg.Done()
3✔
1499

3✔
1500
                                l.Stop()
3✔
1501
                        }(link)
3✔
1502
                }
1503
                wg.Wait()
3✔
1504

3✔
1505
                // Before we exit fully, we'll attempt to flush out any
3✔
1506
                // forwarding events that may still be lingering since the last
3✔
1507
                // batch flush.
3✔
1508
                if err := s.FlushForwardingEvents(); err != nil {
3✔
1509
                        log.Errorf("unable to flush forwarding events: %v", err)
×
1510
                }
×
1511
        }()
1512

1513
        // TODO(roasbeef): cleared vs settled distinction
1514
        var (
3✔
1515
                totalNumUpdates uint64
3✔
1516
                totalSatSent    btcutil.Amount
3✔
1517
                totalSatRecv    btcutil.Amount
3✔
1518
        )
3✔
1519
        s.cfg.LogEventTicker.Resume()
3✔
1520
        defer s.cfg.LogEventTicker.Stop()
3✔
1521

3✔
1522
        // Every 15 seconds, we'll flush out the forwarding events that
3✔
1523
        // occurred during that period.
3✔
1524
        s.cfg.FwdEventTicker.Resume()
3✔
1525
        defer s.cfg.FwdEventTicker.Stop()
3✔
1526

3✔
1527
        defer s.cfg.AckEventTicker.Stop()
3✔
1528

3✔
1529
out:
3✔
1530
        for {
6✔
1531

3✔
1532
                // If the set of pending settle/fail entries is non-zero,
3✔
1533
                // reinstate the ack ticker so we can batch ack them.
3✔
1534
                if len(s.pendingSettleFails) > 0 {
6✔
1535
                        s.cfg.AckEventTicker.Resume()
3✔
1536
                }
3✔
1537

1538
                select {
3✔
1539
                case blockEpoch, ok := <-s.blockEpochStream.Epochs:
3✔
1540
                        if !ok {
3✔
1541
                                break out
×
1542
                        }
1543

1544
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
3✔
1545

1546
                // A local close request has arrived, we'll forward this to the
1547
                // relevant link (if it exists) so the channel can be
1548
                // cooperatively closed (if possible).
1549
                case req := <-s.chanCloseRequests:
3✔
1550
                        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
3✔
1551

3✔
1552
                        s.indexMtx.RLock()
3✔
1553
                        link, ok := s.linkIndex[chanID]
3✔
1554
                        if !ok {
6✔
1555
                                s.indexMtx.RUnlock()
3✔
1556

3✔
1557
                                req.Err <- fmt.Errorf("no peer for channel with "+
3✔
1558
                                        "chan_id=%x", chanID[:])
3✔
1559
                                continue
3✔
1560
                        }
1561
                        s.indexMtx.RUnlock()
3✔
1562

3✔
1563
                        peerPub := link.PeerPubKey()
3✔
1564
                        log.Debugf("Requesting local channel close: peer=%x, "+
3✔
1565
                                "chan_id=%x", link.PeerPubKey(), chanID[:])
3✔
1566

3✔
1567
                        go s.cfg.LocalChannelClose(peerPub[:], req)
3✔
1568

1569
                case resolutionMsg := <-s.resolutionMsgs:
3✔
1570
                        // We'll persist the resolution message to the Switch's
3✔
1571
                        // resolution store.
3✔
1572
                        resMsg := resolutionMsg.ResolutionMsg
3✔
1573
                        err := s.resMsgStore.addResolutionMsg(&resMsg)
3✔
1574
                        if err != nil {
3✔
1575
                                // This will only fail if there is a database
×
1576
                                // error or a serialization error. Sending the
×
1577
                                // error prevents the contractcourt from being
×
1578
                                // in a state where it believes the send was
×
1579
                                // successful, when it wasn't.
×
1580
                                log.Errorf("unable to add resolution msg: %v",
×
1581
                                        err)
×
1582
                                resolutionMsg.errChan <- err
×
1583
                                continue
×
1584
                        }
1585

1586
                        // At this point, the resolution message has been
1587
                        // persisted. It is safe to signal success by sending
1588
                        // a nil error since the Switch will re-deliver the
1589
                        // resolution message on restart.
1590
                        resolutionMsg.errChan <- nil
3✔
1591

3✔
1592
                        // Create a htlc packet for this resolution. We do
3✔
1593
                        // not have some of the information that we'll need
3✔
1594
                        // for blinded error handling here , so we'll rely on
3✔
1595
                        // our forwarding logic to fill it in later.
3✔
1596
                        pkt := &htlcPacket{
3✔
1597
                                outgoingChanID: resolutionMsg.SourceChan,
3✔
1598
                                outgoingHTLCID: resolutionMsg.HtlcIndex,
3✔
1599
                                isResolution:   true,
3✔
1600
                        }
3✔
1601

3✔
1602
                        // Resolution messages will either be cancelling
3✔
1603
                        // backwards an existing HTLC, or settling a previously
3✔
1604
                        // outgoing HTLC. Based on this, we'll map the message
3✔
1605
                        // to the proper htlcPacket.
3✔
1606
                        if resolutionMsg.Failure != nil {
6✔
1607
                                pkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1608
                        } else {
6✔
1609
                                pkt.htlc = &lnwire.UpdateFulfillHTLC{
3✔
1610
                                        PaymentPreimage: *resolutionMsg.PreImage,
3✔
1611
                                }
3✔
1612
                        }
3✔
1613

1614
                        log.Debugf("Received outside contract resolution, "+
3✔
1615
                                "mapping to: %v", spew.Sdump(pkt))
3✔
1616

3✔
1617
                        // We don't check the error, as the only failure we can
3✔
1618
                        // encounter is due to the circuit already being
3✔
1619
                        // closed. This is fine, as processing this message is
3✔
1620
                        // meant to be idempotent.
3✔
1621
                        err = s.handlePacketForward(pkt)
3✔
1622
                        if err != nil {
3✔
1623
                                log.Errorf("Unable to forward resolution msg: %v", err)
×
1624
                        }
×
1625

1626
                // A new packet has arrived for forwarding, we'll interpret the
1627
                // packet concretely, then either forward it along, or
1628
                // interpret a return packet to a locally initialized one.
1629
                case cmd := <-s.htlcPlex:
3✔
1630
                        cmd.err <- s.handlePacketForward(cmd.pkt)
3✔
1631

1632
                // When this time ticks, then it indicates that we should
1633
                // collect all the forwarding events since the last internal,
1634
                // and write them out to our log.
1635
                case <-s.cfg.FwdEventTicker.Ticks():
3✔
1636
                        s.wg.Add(1)
3✔
1637
                        go func() {
6✔
1638
                                defer s.wg.Done()
3✔
1639

3✔
1640
                                if err := s.FlushForwardingEvents(); err != nil {
3✔
1641
                                        log.Errorf("Unable to flush "+
×
1642
                                                "forwarding events: %v", err)
×
1643
                                }
×
1644
                        }()
1645

1646
                // The log ticker has fired, so we'll calculate some forwarding
1647
                // stats for the last 10 seconds to display within the logs to
1648
                // users.
1649
                case <-s.cfg.LogEventTicker.Ticks():
3✔
1650
                        // First, we'll collate the current running tally of
3✔
1651
                        // our forwarding stats.
3✔
1652
                        prevSatSent := totalSatSent
3✔
1653
                        prevSatRecv := totalSatRecv
3✔
1654
                        prevNumUpdates := totalNumUpdates
3✔
1655

3✔
1656
                        var (
3✔
1657
                                newNumUpdates uint64
3✔
1658
                                newSatSent    btcutil.Amount
3✔
1659
                                newSatRecv    btcutil.Amount
3✔
1660
                        )
3✔
1661

3✔
1662
                        // Next, we'll run through all the registered links and
3✔
1663
                        // compute their up-to-date forwarding stats.
3✔
1664
                        s.indexMtx.RLock()
3✔
1665
                        for _, link := range s.linkIndex {
6✔
1666
                                // TODO(roasbeef): when links first registered
3✔
1667
                                // stats printed.
3✔
1668
                                updates, sent, recv := link.Stats()
3✔
1669
                                newNumUpdates += updates
3✔
1670
                                newSatSent += sent.ToSatoshis()
3✔
1671
                                newSatRecv += recv.ToSatoshis()
3✔
1672
                        }
3✔
1673
                        s.indexMtx.RUnlock()
3✔
1674

3✔
1675
                        var (
3✔
1676
                                diffNumUpdates uint64
3✔
1677
                                diffSatSent    btcutil.Amount
3✔
1678
                                diffSatRecv    btcutil.Amount
3✔
1679
                        )
3✔
1680

3✔
1681
                        // If this is the first time we're computing these
3✔
1682
                        // stats, then the diff is just the new value. We do
3✔
1683
                        // this in order to avoid integer underflow issues.
3✔
1684
                        if prevNumUpdates == 0 {
6✔
1685
                                diffNumUpdates = newNumUpdates
3✔
1686
                                diffSatSent = newSatSent
3✔
1687
                                diffSatRecv = newSatRecv
3✔
1688
                        } else {
6✔
1689
                                diffNumUpdates = newNumUpdates - prevNumUpdates
3✔
1690
                                diffSatSent = newSatSent - prevSatSent
3✔
1691
                                diffSatRecv = newSatRecv - prevSatRecv
3✔
1692
                        }
3✔
1693

1694
                        // If the diff of num updates is zero, then we haven't
1695
                        // forwarded anything in the last 10 seconds, so we can
1696
                        // skip this update.
1697
                        if diffNumUpdates == 0 {
6✔
1698
                                continue
3✔
1699
                        }
1700

1701
                        // If the diff of num updates is negative, then some
1702
                        // links may have been unregistered from the switch, so
1703
                        // we'll update our stats to only include our registered
1704
                        // links.
1705
                        if int64(diffNumUpdates) < 0 {
6✔
1706
                                totalNumUpdates = newNumUpdates
3✔
1707
                                totalSatSent = newSatSent
3✔
1708
                                totalSatRecv = newSatRecv
3✔
1709
                                continue
3✔
1710
                        }
1711

1712
                        // Otherwise, we'll log this diff, then accumulate the
1713
                        // new stats into the running total.
1714
                        log.Debugf("Sent %d satoshis and received %d satoshis "+
3✔
1715
                                "in the last 10 seconds (%f tx/sec)",
3✔
1716
                                diffSatSent, diffSatRecv,
3✔
1717
                                float64(diffNumUpdates)/10)
3✔
1718

3✔
1719
                        totalNumUpdates += diffNumUpdates
3✔
1720
                        totalSatSent += diffSatSent
3✔
1721
                        totalSatRecv += diffSatRecv
3✔
1722

1723
                // The ack ticker has fired so if we have any settle/fail entries
1724
                // for a forwarding package to ack, we will do so here in a batch
1725
                // db call.
1726
                case <-s.cfg.AckEventTicker.Ticks():
3✔
1727
                        // If the current set is empty, pause the ticker.
3✔
1728
                        if len(s.pendingSettleFails) == 0 {
6✔
1729
                                s.cfg.AckEventTicker.Pause()
3✔
1730
                                continue
3✔
1731
                        }
1732

1733
                        // Batch ack the settle/fail entries.
1734
                        if err := s.ackSettleFail(s.pendingSettleFails...); err != nil {
3✔
1735
                                log.Errorf("Unable to ack batch of settle/fails: %v", err)
×
1736
                                continue
×
1737
                        }
1738

1739
                        log.Tracef("Acked %d settle fails: %v",
3✔
1740
                                len(s.pendingSettleFails),
3✔
1741
                                lnutils.SpewLogClosure(s.pendingSettleFails))
3✔
1742

3✔
1743
                        // Reset the pendingSettleFails buffer while keeping acquired
3✔
1744
                        // memory.
3✔
1745
                        s.pendingSettleFails = s.pendingSettleFails[:0]
3✔
1746

1747
                case <-s.quit:
3✔
1748
                        return
3✔
1749
                }
1750
        }
1751
}
1752

1753
// Start starts all helper goroutines required for the operation of the switch.
1754
func (s *Switch) Start() error {
3✔
1755
        if !atomic.CompareAndSwapInt32(&s.started, 0, 1) {
3✔
1756
                log.Warn("Htlc Switch already started")
×
1757
                return errors.New("htlc switch already started")
×
1758
        }
×
1759

1760
        log.Infof("HTLC Switch starting")
3✔
1761

3✔
1762
        blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
1763
        if err != nil {
3✔
1764
                return err
×
1765
        }
×
1766
        s.blockEpochStream = blockEpochStream
3✔
1767

3✔
1768
        s.wg.Add(1)
3✔
1769
        go s.htlcForwarder()
3✔
1770

3✔
1771
        if err := s.reforwardResponses(); err != nil {
3✔
1772
                s.Stop()
×
1773
                log.Errorf("unable to reforward responses: %v", err)
×
1774
                return err
×
1775
        }
×
1776

1777
        if err := s.reforwardResolutions(); err != nil {
3✔
1778
                // We are already stopping so we can ignore the error.
×
1779
                _ = s.Stop()
×
1780
                log.Errorf("unable to reforward resolutions: %v", err)
×
1781
                return err
×
1782
        }
×
1783

1784
        return nil
3✔
1785
}
1786

1787
// reforwardResolutions fetches the set of resolution messages stored on-disk
1788
// and reforwards them if their circuits are still open. If the circuits have
1789
// been deleted, then we will delete the resolution message from the database.
1790
func (s *Switch) reforwardResolutions() error {
3✔
1791
        // Fetch all stored resolution messages, deleting the ones that are
3✔
1792
        // resolved.
3✔
1793
        resMsgs, err := s.resMsgStore.fetchAllResolutionMsg()
3✔
1794
        if err != nil {
3✔
1795
                return err
×
1796
        }
×
1797

1798
        switchPackets := make([]*htlcPacket, 0, len(resMsgs))
3✔
1799
        for _, resMsg := range resMsgs {
6✔
1800
                // If the open circuit no longer exists, then we can remove the
3✔
1801
                // message from the store.
3✔
1802
                outKey := CircuitKey{
3✔
1803
                        ChanID: resMsg.SourceChan,
3✔
1804
                        HtlcID: resMsg.HtlcIndex,
3✔
1805
                }
3✔
1806

3✔
1807
                if s.circuits.LookupOpenCircuit(outKey) == nil {
6✔
1808
                        // The open circuit doesn't exist.
3✔
1809
                        err := s.resMsgStore.deleteResolutionMsg(&outKey)
3✔
1810
                        if err != nil {
3✔
1811
                                return err
×
1812
                        }
×
1813

1814
                        continue
3✔
1815
                }
1816

1817
                // The circuit is still open, so we can assume that the link or
1818
                // switch (if we are the source) hasn't cleaned it up yet.
1819
                // We rely on our forwarding logic to fill in details that
1820
                // are not currently available to us.
1821
                resPkt := &htlcPacket{
3✔
1822
                        outgoingChanID: resMsg.SourceChan,
3✔
1823
                        outgoingHTLCID: resMsg.HtlcIndex,
3✔
1824
                        isResolution:   true,
3✔
1825
                }
3✔
1826

3✔
1827
                if resMsg.Failure != nil {
6✔
1828
                        resPkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1829
                } else {
3✔
1830
                        resPkt.htlc = &lnwire.UpdateFulfillHTLC{
×
1831
                                PaymentPreimage: *resMsg.PreImage,
×
1832
                        }
×
1833
                }
×
1834

1835
                switchPackets = append(switchPackets, resPkt)
3✔
1836
        }
1837

1838
        // We'll now dispatch the set of resolution messages to the proper
1839
        // destination. An error is only encountered here if the switch is
1840
        // shutting down.
1841
        if err := s.ForwardPackets(nil, switchPackets...); err != nil {
3✔
1842
                return err
×
1843
        }
×
1844

1845
        return nil
3✔
1846
}
1847

1848
// reforwardResponses for every known, non-pending channel, loads all associated
1849
// forwarding packages and reforwards any Settle or Fail HTLCs found. This is
1850
// used to resurrect the switch's mailboxes after a restart. This also runs for
1851
// waiting close channels since there may be settles or fails that need to be
1852
// reforwarded before they completely close.
1853
func (s *Switch) reforwardResponses() error {
3✔
1854
        openChannels, err := s.cfg.FetchAllChannels()
3✔
1855
        if err != nil {
3✔
1856
                return err
×
1857
        }
×
1858

1859
        for _, openChannel := range openChannels {
6✔
1860
                shortChanID := openChannel.ShortChanID()
3✔
1861

3✔
1862
                // Locally-initiated payments never need reforwarding.
3✔
1863
                if shortChanID == hop.Source {
6✔
1864
                        continue
3✔
1865
                }
1866

1867
                // If the channel is pending, it should have no forwarding
1868
                // packages, and nothing to reforward.
1869
                if openChannel.IsPending {
3✔
1870
                        continue
×
1871
                }
1872

1873
                // Channels in open or waiting-close may still have responses in
1874
                // their forwarding packages. We will continue to reattempt
1875
                // forwarding on startup until the channel is fully-closed.
1876
                //
1877
                // Load this channel's forwarding packages, and deliver them to
1878
                // the switch.
1879
                fwdPkgs, err := s.loadChannelFwdPkgs(shortChanID)
3✔
1880
                if err != nil {
3✔
1881
                        log.Errorf("unable to load forwarding "+
×
1882
                                "packages for %v: %v", shortChanID, err)
×
1883
                        return err
×
1884
                }
×
1885

1886
                s.reforwardSettleFails(fwdPkgs)
3✔
1887
        }
1888

1889
        return nil
3✔
1890
}
1891

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

3✔
1896
        var fwdPkgs []*channeldb.FwdPkg
3✔
1897
        if err := kvdb.View(s.cfg.DB, func(tx kvdb.RTx) error {
6✔
1898
                var err error
3✔
1899
                fwdPkgs, err = s.cfg.SwitchPackager.LoadChannelFwdPkgs(
3✔
1900
                        tx, source,
3✔
1901
                )
3✔
1902
                return err
3✔
1903
        }, func() {
6✔
1904
                fwdPkgs = nil
3✔
1905
        }); err != nil {
3✔
1906
                return nil, err
×
1907
        }
×
1908

1909
        return fwdPkgs, nil
3✔
1910
}
1911

1912
// reforwardSettleFails parses the Settle and Fail HTLCs from the list of
1913
// forwarding packages, and reforwards those that have not been acknowledged.
1914
// This is intended to occur on startup, in order to recover the switch's
1915
// mailboxes, and to ensure that responses can be propagated in case the
1916
// outgoing link never comes back online.
1917
//
1918
// NOTE: This should mimic the behavior processRemoteSettleFails.
1919
func (s *Switch) reforwardSettleFails(fwdPkgs []*channeldb.FwdPkg) {
3✔
1920
        for _, fwdPkg := range fwdPkgs {
6✔
1921
                switchPackets := make([]*htlcPacket, 0, len(fwdPkg.SettleFails))
3✔
1922
                for i, update := range fwdPkg.SettleFails {
6✔
1923
                        // Skip any settles or fails that have already been
3✔
1924
                        // acknowledged by the incoming link that originated the
3✔
1925
                        // forwarded Add.
3✔
1926
                        if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
6✔
1927
                                continue
3✔
1928
                        }
1929

1930
                        switch msg := update.UpdateMsg.(type) {
3✔
1931
                        // A settle for an HTLC we previously forwarded HTLC has
1932
                        // been received. So we'll forward the HTLC to the
1933
                        // switch which will handle propagating the settle to
1934
                        // the prior hop.
1935
                        case *lnwire.UpdateFulfillHTLC:
3✔
1936
                                destRef := fwdPkg.DestRef(uint16(i))
3✔
1937
                                settlePacket := &htlcPacket{
3✔
1938
                                        outgoingChanID: fwdPkg.Source,
3✔
1939
                                        outgoingHTLCID: msg.ID,
3✔
1940
                                        destRef:        &destRef,
3✔
1941
                                        htlc:           msg,
3✔
1942
                                }
3✔
1943

3✔
1944
                                // Add the packet to the batch to be forwarded, and
3✔
1945
                                // notify the overflow queue that a spare spot has been
3✔
1946
                                // freed up within the commitment state.
3✔
1947
                                switchPackets = append(switchPackets, settlePacket)
3✔
1948

1949
                        // A failureCode message for a previously forwarded HTLC has been
1950
                        // received. As a result a new slot will be freed up in our
1951
                        // commitment state, so we'll forward this to the switch so the
1952
                        // backwards undo can continue.
1953
                        case *lnwire.UpdateFailHTLC:
×
1954
                                // Fetch the reason the HTLC was canceled so
×
1955
                                // we can continue to propagate it. This
×
1956
                                // failure originated from another node, so
×
1957
                                // the linkFailure field is not set on this
×
1958
                                // packet. We rely on the link to fill in
×
1959
                                // additional circuit information for us.
×
1960
                                failPacket := &htlcPacket{
×
1961
                                        outgoingChanID: fwdPkg.Source,
×
1962
                                        outgoingHTLCID: msg.ID,
×
1963
                                        destRef: &channeldb.SettleFailRef{
×
1964
                                                Source: fwdPkg.Source,
×
1965
                                                Height: fwdPkg.Height,
×
1966
                                                Index:  uint16(i),
×
1967
                                        },
×
1968
                                        htlc: msg,
×
1969
                                }
×
1970

×
1971
                                // Add the packet to the batch to be forwarded, and
×
1972
                                // notify the overflow queue that a spare spot has been
×
1973
                                // freed up within the commitment state.
×
1974
                                switchPackets = append(switchPackets, failPacket)
×
1975
                        }
1976
                }
1977

1978
                // Since this send isn't tied to a specific link, we pass a nil
1979
                // link quit channel, meaning the send will fail only if the
1980
                // switch receives a shutdown request.
1981
                if err := s.ForwardPackets(nil, switchPackets...); err != nil {
3✔
1982
                        log.Errorf("Unhandled error while reforwarding packets "+
×
1983
                                "settle/fail over htlcswitch: %v", err)
×
1984
                }
×
1985
        }
1986
}
1987

1988
// Stop gracefully stops all active helper goroutines, then waits until they've
1989
// exited.
1990
func (s *Switch) Stop() error {
3✔
1991
        if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
3✔
UNCOV
1992
                log.Warn("Htlc Switch already stopped")
×
UNCOV
1993
                return errors.New("htlc switch already shutdown")
×
UNCOV
1994
        }
×
1995

1996
        log.Info("HTLC Switch shutting down...")
3✔
1997
        defer log.Debug("HTLC Switch shutdown complete")
3✔
1998

3✔
1999
        close(s.quit)
3✔
2000

3✔
2001
        s.wg.Wait()
3✔
2002

3✔
2003
        // Wait until all active goroutines have finished exiting before
3✔
2004
        // stopping the mailboxes, otherwise the mailbox map could still be
3✔
2005
        // accessed and modified.
3✔
2006
        s.mailOrchestrator.Stop()
3✔
2007

3✔
2008
        return nil
3✔
2009
}
2010

2011
// CreateAndAddLink will create a link and then add it to the internal maps
2012
// when given a ChannelLinkConfig and LightningChannel.
2013
func (s *Switch) CreateAndAddLink(linkCfg ChannelLinkConfig,
2014
        lnChan *lnwallet.LightningChannel) error {
3✔
2015

3✔
2016
        link := NewChannelLink(linkCfg, lnChan)
3✔
2017
        return s.AddLink(link)
3✔
2018
}
3✔
2019

2020
// AddLink is used to initiate the handling of the add link command. The
2021
// request will be propagated and handled in the main goroutine.
2022
func (s *Switch) AddLink(link ChannelLink) error {
3✔
2023
        s.indexMtx.Lock()
3✔
2024
        defer s.indexMtx.Unlock()
3✔
2025

3✔
2026
        chanID := link.ChanID()
3✔
2027

3✔
2028
        // First, ensure that this link is not already active in the switch.
3✔
2029
        _, err := s.getLink(chanID)
3✔
2030
        if err == nil {
3✔
UNCOV
2031
                return fmt.Errorf("unable to add ChannelLink(%v), already "+
×
UNCOV
2032
                        "active", chanID)
×
UNCOV
2033
        }
×
2034

2035
        // Get and attach the mailbox for this link, which buffers packets in
2036
        // case there packets that we tried to deliver while this link was
2037
        // offline.
2038
        shortChanID := link.ShortChanID()
3✔
2039
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(chanID, shortChanID)
3✔
2040
        link.AttachMailBox(mailbox)
3✔
2041

3✔
2042
        // Attach the Switch's failAliasUpdate function to the link.
3✔
2043
        link.attachFailAliasUpdate(s.failAliasUpdate)
3✔
2044

3✔
2045
        if err := link.Start(); err != nil {
3✔
2046
                log.Errorf("AddLink failed to start link with chanID=%v: %v",
×
2047
                        chanID, err)
×
2048
                s.removeLink(chanID)
×
2049
                return err
×
2050
        }
×
2051

2052
        if shortChanID == hop.Source {
6✔
2053
                log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
3✔
2054
                        chanID, shortChanID)
3✔
2055

3✔
2056
                s.pendingLinkIndex[chanID] = link
3✔
2057
        } else {
6✔
2058
                log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
3✔
2059
                        chanID, shortChanID)
3✔
2060

3✔
2061
                s.addLiveLink(link)
3✔
2062
                s.mailOrchestrator.BindLiveShortChanID(
3✔
2063
                        mailbox, chanID, shortChanID,
3✔
2064
                )
3✔
2065
        }
3✔
2066

2067
        return nil
3✔
2068
}
2069

2070
// addLiveLink adds a link to all associated forwarding index, this makes it a
2071
// candidate for forwarding HTLCs.
2072
func (s *Switch) addLiveLink(link ChannelLink) {
3✔
2073
        linkScid := link.ShortChanID()
3✔
2074

3✔
2075
        // We'll add the link to the linkIndex which lets us quickly
3✔
2076
        // look up a channel when we need to close or register it, and
3✔
2077
        // the forwarding index which'll be used when forwarding HTLC's
3✔
2078
        // in the multi-hop setting.
3✔
2079
        s.linkIndex[link.ChanID()] = link
3✔
2080
        s.forwardingIndex[linkScid] = link
3✔
2081

3✔
2082
        // Next we'll add the link to the interface index so we can
3✔
2083
        // quickly look up all the channels for a particular node.
3✔
2084
        peerPub := link.PeerPubKey()
3✔
2085
        if _, ok := s.interfaceIndex[peerPub]; !ok {
6✔
2086
                s.interfaceIndex[peerPub] = make(map[lnwire.ChannelID]ChannelLink)
3✔
2087
        }
3✔
2088
        s.interfaceIndex[peerPub][link.ChanID()] = link
3✔
2089

3✔
2090
        s.updateLinkAliases(link)
3✔
2091
}
2092

2093
// UpdateLinkAliases is the externally exposed wrapper for updating link
2094
// aliases. It acquires the indexMtx and calls the internal method.
2095
func (s *Switch) UpdateLinkAliases(link ChannelLink) {
3✔
2096
        s.indexMtx.Lock()
3✔
2097
        defer s.indexMtx.Unlock()
3✔
2098

3✔
2099
        s.updateLinkAliases(link)
3✔
2100
}
3✔
2101

2102
// updateLinkAliases updates the aliases for a given link. This will cause the
2103
// htlcswitch to consult the alias manager on the up to date values of its
2104
// alias maps.
2105
//
2106
// NOTE: this MUST be called with the indexMtx held.
2107
func (s *Switch) updateLinkAliases(link ChannelLink) {
3✔
2108
        linkScid := link.ShortChanID()
3✔
2109

3✔
2110
        aliases := link.getAliases()
3✔
2111
        if link.isZeroConf() {
6✔
2112
                if link.zeroConfConfirmed() {
6✔
2113
                        // Since the zero-conf channel has confirmed, we can
3✔
2114
                        // populate the aliasToReal mapping.
3✔
2115
                        confirmedScid := link.confirmedScid()
3✔
2116

3✔
2117
                        for _, alias := range aliases {
6✔
2118
                                s.aliasToReal[alias] = confirmedScid
3✔
2119
                        }
3✔
2120

2121
                        // Add the confirmed SCID as a key in the baseIndex.
2122
                        s.baseIndex[confirmedScid] = linkScid
3✔
2123
                }
2124

2125
                // Now we populate the baseIndex which will be used to fetch
2126
                // the link given any of the channel's alias SCIDs or the real
2127
                // SCID. The link's SCID is an alias, so we don't need to
2128
                // special-case it like the option-scid-alias feature-bit case
2129
                // further down.
2130
                for _, alias := range aliases {
6✔
2131
                        s.baseIndex[alias] = linkScid
3✔
2132
                }
3✔
2133
        } else if link.negotiatedAliasFeature() {
6✔
2134
                // First, we flush any alias mappings for this link's scid
3✔
2135
                // before we populate the map again, in order to get rid of old
3✔
2136
                // values that no longer exist.
3✔
2137
                for alias, real := range s.aliasToReal {
6✔
2138
                        if real == linkScid {
6✔
2139
                                delete(s.aliasToReal, alias)
3✔
2140
                        }
3✔
2141
                }
2142

2143
                for alias, real := range s.baseIndex {
6✔
2144
                        if real == linkScid {
6✔
2145
                                delete(s.baseIndex, alias)
3✔
2146
                        }
3✔
2147
                }
2148

2149
                // The link's SCID is the confirmed SCID for non-zero-conf
2150
                // option-scid-alias feature bit channels.
2151
                for _, alias := range aliases {
6✔
2152
                        s.aliasToReal[alias] = linkScid
3✔
2153
                        s.baseIndex[alias] = linkScid
3✔
2154
                }
3✔
2155

2156
                // Since the link's SCID is confirmed, it was not included in
2157
                // the baseIndex above as a key. Add it now.
2158
                s.baseIndex[linkScid] = linkScid
3✔
2159
        }
2160
}
2161

2162
// GetLink is used to initiate the handling of the get link command. The
2163
// request will be propagated/handled to/in the main goroutine.
2164
func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelUpdateHandler,
2165
        error) {
3✔
2166

3✔
2167
        s.indexMtx.RLock()
3✔
2168
        defer s.indexMtx.RUnlock()
3✔
2169

3✔
2170
        return s.getLink(chanID)
3✔
2171
}
3✔
2172

2173
// getLink returns the link stored in either the pending index or the live
2174
// lindex.
2175
func (s *Switch) getLink(chanID lnwire.ChannelID) (ChannelLink, error) {
3✔
2176
        link, ok := s.linkIndex[chanID]
3✔
2177
        if !ok {
6✔
2178
                link, ok = s.pendingLinkIndex[chanID]
3✔
2179
                if !ok {
6✔
2180
                        return nil, ErrChannelLinkNotFound
3✔
2181
                }
3✔
2182
        }
2183

2184
        return link, nil
3✔
2185
}
2186

2187
// GetLinkByShortID attempts to return the link which possesses the target short
2188
// channel ID.
2189
func (s *Switch) GetLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink,
2190
        error) {
3✔
2191

3✔
2192
        s.indexMtx.RLock()
3✔
2193
        defer s.indexMtx.RUnlock()
3✔
2194

3✔
2195
        link, err := s.getLinkByShortID(chanID)
3✔
2196
        if err != nil {
6✔
2197
                // If we failed to find the link under the passed-in SCID, we
3✔
2198
                // consult the Switch's baseIndex map to see if the confirmed
3✔
2199
                // SCID was used for a zero-conf channel.
3✔
2200
                aliasID, ok := s.baseIndex[chanID]
3✔
2201
                if !ok {
6✔
2202
                        return nil, err
3✔
2203
                }
3✔
2204

2205
                // An alias was found, use it to lookup if a link exists.
2206
                return s.getLinkByShortID(aliasID)
3✔
2207
        }
2208

2209
        return link, nil
3✔
2210
}
2211

2212
// getLinkByShortID attempts to return the link which possesses the target
2213
// short channel ID.
2214
//
2215
// NOTE: This MUST be called with the indexMtx held.
2216
func (s *Switch) getLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink, error) {
3✔
2217
        link, ok := s.forwardingIndex[chanID]
3✔
2218
        if !ok {
6✔
2219
                return nil, ErrChannelLinkNotFound
3✔
2220
        }
3✔
2221

2222
        return link, nil
3✔
2223
}
2224

2225
// getLinkByMapping attempts to fetch the link via the htlcPacket's
2226
// outgoingChanID, possibly using a mapping. If it finds the link via mapping,
2227
// the outgoingChanID will be changed so that an error can be properly
2228
// attributed when looping over linkErrs in handlePacketForward.
2229
//
2230
// * If the outgoingChanID is an alias, we'll fetch the link regardless if it's
2231
// public or not.
2232
//
2233
// * If the outgoingChanID is a confirmed SCID, we'll need to do more checks.
2234
//   - If there is no entry found in baseIndex, fetch the link. This channel
2235
//     did not have the option-scid-alias feature negotiated (which includes
2236
//     zero-conf and option-scid-alias channel-types).
2237
//   - If there is an entry found, fetch the link from forwardingIndex and
2238
//     fail if this is a private link.
2239
//
2240
// NOTE: This MUST be called with the indexMtx read lock held.
2241
func (s *Switch) getLinkByMapping(pkt *htlcPacket) (ChannelLink, error) {
3✔
2242
        // Determine if this ShortChannelID is an alias or a confirmed SCID.
3✔
2243
        chanID := pkt.outgoingChanID
3✔
2244
        aliasID := s.cfg.IsAlias(chanID)
3✔
2245

3✔
2246
        // Set the originalOutgoingChanID so the proper channel_update can be
3✔
2247
        // sent back if the option-scid-alias feature bit was negotiated.
3✔
2248
        pkt.originalOutgoingChanID = chanID
3✔
2249

3✔
2250
        if aliasID {
6✔
2251
                // Since outgoingChanID is an alias, we'll fetch the link via
3✔
2252
                // baseIndex.
3✔
2253
                baseScid, ok := s.baseIndex[chanID]
3✔
2254
                if !ok {
3✔
2255
                        // No mapping exists, bail.
×
2256
                        return nil, ErrChannelLinkNotFound
×
2257
                }
×
2258

2259
                // A mapping exists, so use baseScid to find the link in the
2260
                // forwardingIndex.
2261
                link, ok := s.forwardingIndex[baseScid]
3✔
2262
                if !ok {
3✔
2263
                        // Link not found, bail.
×
2264
                        return nil, ErrChannelLinkNotFound
×
2265
                }
×
2266

2267
                // Change the packet's outgoingChanID field so that errors are
2268
                // properly attributed.
2269
                pkt.outgoingChanID = baseScid
3✔
2270

3✔
2271
                // Return the link without checking if it's private or not.
3✔
2272
                return link, nil
3✔
2273
        }
2274

2275
        // The outgoingChanID is a confirmed SCID. Attempt to fetch the base
2276
        // SCID from baseIndex.
2277
        baseScid, ok := s.baseIndex[chanID]
3✔
2278
        if !ok {
6✔
2279
                // outgoingChanID is not a key in base index meaning this
3✔
2280
                // channel did not have the option-scid-alias feature bit
3✔
2281
                // negotiated. We'll fetch the link and return it.
3✔
2282
                link, ok := s.forwardingIndex[chanID]
3✔
2283
                if !ok {
6✔
2284
                        // The link wasn't found, bail out.
3✔
2285
                        return nil, ErrChannelLinkNotFound
3✔
2286
                }
3✔
2287

2288
                return link, nil
3✔
2289
        }
2290

2291
        // Fetch the link whose internal SCID is baseScid.
2292
        link, ok := s.forwardingIndex[baseScid]
3✔
2293
        if !ok {
3✔
2294
                // Link wasn't found, bail out.
×
2295
                return nil, ErrChannelLinkNotFound
×
2296
        }
×
2297

2298
        // If the link is unadvertised, we fail since the real SCID was used to
2299
        // forward over it and this is a channel where the option-scid-alias
2300
        // feature bit was negotiated.
2301
        if link.IsUnadvertised() {
3✔
UNCOV
2302
                return nil, ErrChannelLinkNotFound
×
UNCOV
2303
        }
×
2304

2305
        // The link is public so the confirmed SCID can be used to forward over
2306
        // it. We'll also replace pkt's outgoingChanID field so errors can
2307
        // properly be attributed in the calling function.
2308
        pkt.outgoingChanID = baseScid
3✔
2309
        return link, nil
3✔
2310
}
2311

2312
// HasActiveLink returns true if the given channel ID has a link in the link
2313
// index AND the link is eligible to forward.
2314
func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
3✔
2315
        s.indexMtx.RLock()
3✔
2316
        defer s.indexMtx.RUnlock()
3✔
2317

3✔
2318
        if link, ok := s.linkIndex[chanID]; ok {
6✔
2319
                return link.EligibleToForward()
3✔
2320
        }
3✔
2321

2322
        return false
3✔
2323
}
2324

2325
// RemoveLink purges the switch of any link associated with chanID. If a pending
2326
// or active link is not found, this method does nothing. Otherwise, the method
2327
// returns after the link has been completely shutdown.
2328
func (s *Switch) RemoveLink(chanID lnwire.ChannelID) {
3✔
2329
        s.indexMtx.Lock()
3✔
2330
        link, err := s.getLink(chanID)
3✔
2331
        if err != nil {
6✔
2332
                // If err is non-nil, this means that link is also nil. The
3✔
2333
                // link variable cannot be nil without err being non-nil.
3✔
2334
                s.indexMtx.Unlock()
3✔
2335
                log.Tracef("Unable to remove link for ChannelID(%v): %v",
3✔
2336
                        chanID, err)
3✔
2337
                return
3✔
2338
        }
3✔
2339

2340
        // Check if the link is already stopping and grab the stop chan if it
2341
        // is.
2342
        stopChan, ok := s.linkStopIndex[chanID]
3✔
2343
        if !ok {
6✔
2344
                // If the link is non-nil, it is not currently stopping, so
3✔
2345
                // we'll add a stop chan to the linkStopIndex.
3✔
2346
                stopChan = make(chan struct{})
3✔
2347
                s.linkStopIndex[chanID] = stopChan
3✔
2348
        }
3✔
2349
        s.indexMtx.Unlock()
3✔
2350

3✔
2351
        if ok {
3✔
2352
                // If the stop chan exists, we will wait for it to be closed.
×
2353
                // Once it is closed, we will exit.
×
2354
                select {
×
2355
                case <-stopChan:
×
2356
                        return
×
2357
                case <-s.quit:
×
2358
                        return
×
2359
                }
2360
        }
2361

2362
        // Stop the link before removing it from the maps.
2363
        link.Stop()
3✔
2364

3✔
2365
        s.indexMtx.Lock()
3✔
2366
        _ = s.removeLink(chanID)
3✔
2367

3✔
2368
        // Close stopChan and remove this link from the linkStopIndex.
3✔
2369
        // Deleting from the index and removing from the link must be done
3✔
2370
        // in the same block while the mutex is held.
3✔
2371
        close(stopChan)
3✔
2372
        delete(s.linkStopIndex, chanID)
3✔
2373
        s.indexMtx.Unlock()
3✔
2374
}
2375

2376
// removeLink is used to remove and stop the channel link.
2377
//
2378
// NOTE: This MUST be called with the indexMtx held.
2379
func (s *Switch) removeLink(chanID lnwire.ChannelID) ChannelLink {
3✔
2380
        log.Infof("Removing channel link with ChannelID(%v)", chanID)
3✔
2381

3✔
2382
        link, err := s.getLink(chanID)
3✔
2383
        if err != nil {
3✔
2384
                return nil
×
2385
        }
×
2386

2387
        // Remove the channel from live link indexes.
2388
        delete(s.pendingLinkIndex, link.ChanID())
3✔
2389
        delete(s.linkIndex, link.ChanID())
3✔
2390
        delete(s.forwardingIndex, link.ShortChanID())
3✔
2391

3✔
2392
        // If the link has been added to the peer index, then we'll move to
3✔
2393
        // delete the entry within the index.
3✔
2394
        peerPub := link.PeerPubKey()
3✔
2395
        if peerIndex, ok := s.interfaceIndex[peerPub]; ok {
6✔
2396
                delete(peerIndex, link.ChanID())
3✔
2397

3✔
2398
                // If after deletion, there are no longer any links, then we'll
3✔
2399
                // remove the interface map all together.
3✔
2400
                if len(peerIndex) == 0 {
6✔
2401
                        delete(s.interfaceIndex, peerPub)
3✔
2402
                }
3✔
2403
        }
2404

2405
        return link
3✔
2406
}
2407

2408
// UpdateShortChanID locates the link with the passed-in chanID and updates the
2409
// underlying channel state. This is only used in zero-conf channels to allow
2410
// the confirmed SCID to be updated.
2411
func (s *Switch) UpdateShortChanID(chanID lnwire.ChannelID) error {
3✔
2412
        s.indexMtx.Lock()
3✔
2413
        defer s.indexMtx.Unlock()
3✔
2414

3✔
2415
        // Locate the target link in the link index. If no such link exists,
3✔
2416
        // then we will ignore the request.
3✔
2417
        link, ok := s.linkIndex[chanID]
3✔
2418
        if !ok {
3✔
2419
                return fmt.Errorf("link %v not found", chanID)
×
2420
        }
×
2421

2422
        // Try to update the link's underlying channel state, returning early
2423
        // if this update failed.
2424
        _, err := link.UpdateShortChanID()
3✔
2425
        if err != nil {
3✔
2426
                return err
×
2427
        }
×
2428

2429
        // Since the zero-conf channel is confirmed, we should populate the
2430
        // aliasToReal map and update the baseIndex.
2431
        aliases := link.getAliases()
3✔
2432

3✔
2433
        confirmedScid := link.confirmedScid()
3✔
2434

3✔
2435
        for _, alias := range aliases {
6✔
2436
                s.aliasToReal[alias] = confirmedScid
3✔
2437
        }
3✔
2438

2439
        s.baseIndex[confirmedScid] = link.ShortChanID()
3✔
2440

3✔
2441
        return nil
3✔
2442
}
2443

2444
// GetLinksByInterface fetches all the links connected to a particular node
2445
// identified by the serialized compressed form of its public key.
2446
func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
2447
        error) {
3✔
2448

3✔
2449
        s.indexMtx.RLock()
3✔
2450
        defer s.indexMtx.RUnlock()
3✔
2451

3✔
2452
        var handlers []ChannelUpdateHandler
3✔
2453

3✔
2454
        links, err := s.getLinks(hop)
3✔
2455
        if err != nil {
6✔
2456
                return nil, err
3✔
2457
        }
3✔
2458

2459
        // Range over the returned []ChannelLink to convert them into
2460
        // []ChannelUpdateHandler.
2461
        for _, link := range links {
6✔
2462
                handlers = append(handlers, link)
3✔
2463
        }
3✔
2464

2465
        return handlers, nil
3✔
2466
}
2467

2468
// getLinks is function which returns the channel links of the peer by hop
2469
// destination id.
2470
//
2471
// NOTE: This MUST be called with the indexMtx held.
2472
func (s *Switch) getLinks(destination [33]byte) ([]ChannelLink, error) {
3✔
2473
        links, ok := s.interfaceIndex[destination]
3✔
2474
        if !ok {
6✔
2475
                return nil, ErrNoLinksFound
3✔
2476
        }
3✔
2477

2478
        channelLinks := make([]ChannelLink, 0, len(links))
3✔
2479
        for _, link := range links {
6✔
2480
                channelLinks = append(channelLinks, link)
3✔
2481
        }
3✔
2482

2483
        return channelLinks, nil
3✔
2484
}
2485

2486
// CircuitModifier returns a reference to subset of the interfaces provided by
2487
// the circuit map, to allow links to open and close circuits.
2488
func (s *Switch) CircuitModifier() CircuitModifier {
3✔
2489
        return s.circuits
3✔
2490
}
3✔
2491

2492
// CircuitLookup returns a reference to subset of the interfaces provided by the
2493
// circuit map, to allow looking up circuits.
2494
func (s *Switch) CircuitLookup() CircuitLookup {
3✔
2495
        return s.circuits
3✔
2496
}
3✔
2497

2498
// commitCircuits persistently adds a circuit to the switch's circuit map.
2499
func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
UNCOV
2500
        *CircuitFwdActions, error) {
×
UNCOV
2501

×
UNCOV
2502
        return s.circuits.CommitCircuits(circuits...)
×
UNCOV
2503
}
×
2504

2505
// FlushForwardingEvents flushes out the set of pending forwarding events to
2506
// the persistent log. This will be used by the switch to periodically flush
2507
// out the set of forwarding events to disk. External callers can also use this
2508
// method to ensure all data is flushed to dis before querying the log.
2509
func (s *Switch) FlushForwardingEvents() error {
3✔
2510
        // First, we'll obtain a copy of the current set of pending forwarding
3✔
2511
        // events.
3✔
2512
        s.fwdEventMtx.Lock()
3✔
2513

3✔
2514
        // If we won't have any forwarding events, then we can exit early.
3✔
2515
        if len(s.pendingFwdingEvents) == 0 {
6✔
2516
                s.fwdEventMtx.Unlock()
3✔
2517
                return nil
3✔
2518
        }
3✔
2519

2520
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
3✔
2521
        copy(events[:], s.pendingFwdingEvents[:])
3✔
2522

3✔
2523
        // With the copy obtained, we can now clear out the header pointer of
3✔
2524
        // the current slice. This way, we can re-use the underlying storage
3✔
2525
        // allocated for the slice.
3✔
2526
        s.pendingFwdingEvents = s.pendingFwdingEvents[:0]
3✔
2527
        s.fwdEventMtx.Unlock()
3✔
2528

3✔
2529
        // Finally, we'll write out the copied events to the persistent
3✔
2530
        // forwarding log.
3✔
2531
        return s.cfg.FwdingLog.AddForwardingEvents(events)
3✔
2532
}
2533

2534
// BestHeight returns the best height known to the switch.
2535
func (s *Switch) BestHeight() uint32 {
3✔
2536
        return atomic.LoadUint32(&s.bestHeight)
3✔
2537
}
3✔
2538

2539
// dustExceedsFeeThreshold takes in a ChannelLink, HTLC amount, and a boolean
2540
// to determine whether the default fee threshold has been exceeded. This
2541
// heuristic takes into account the trimmed-to-dust mechanism. The sum of the
2542
// commitment's dust with the mailbox's dust with the amount is checked against
2543
// the fee exposure threshold. If incoming is true, then the amount is not
2544
// included in the sum as it was already included in the commitment's dust. A
2545
// boolean is returned telling the caller whether the HTLC should be failed
2546
// back.
2547
func (s *Switch) dustExceedsFeeThreshold(link ChannelLink,
2548
        amount lnwire.MilliSatoshi, incoming bool) bool {
3✔
2549

3✔
2550
        // Retrieve the link's current commitment feerate and dustClosure.
3✔
2551
        feeRate := link.getFeeRate()
3✔
2552
        isDust := link.getDustClosure()
3✔
2553

3✔
2554
        // Evaluate if the HTLC is dust on either sides' commitment.
3✔
2555
        isLocalDust := isDust(
3✔
2556
                feeRate, incoming, lntypes.Local, amount.ToSatoshis(),
3✔
2557
        )
3✔
2558
        isRemoteDust := isDust(
3✔
2559
                feeRate, incoming, lntypes.Remote, amount.ToSatoshis(),
3✔
2560
        )
3✔
2561

3✔
2562
        if !(isLocalDust || isRemoteDust) {
6✔
2563
                // If the HTLC is not dust on either commitment, it's fine to
3✔
2564
                // forward.
3✔
2565
                return false
3✔
2566
        }
3✔
2567

2568
        // Fetch the dust sums currently in the mailbox for this link.
2569
        cid := link.ChanID()
3✔
2570
        sid := link.ShortChanID()
3✔
2571
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
3✔
2572
        localMailDust, remoteMailDust := mailbox.DustPackets()
3✔
2573

3✔
2574
        // If the htlc is dust on the local commitment, we'll obtain the dust
3✔
2575
        // sum for it.
3✔
2576
        if isLocalDust {
6✔
2577
                localSum := link.getDustSum(
3✔
2578
                        lntypes.Local, fn.None[chainfee.SatPerKWeight](),
3✔
2579
                )
3✔
2580
                localSum += localMailDust
3✔
2581

3✔
2582
                // Optionally include the HTLC amount only for outgoing
3✔
2583
                // HTLCs.
3✔
2584
                if !incoming {
6✔
2585
                        localSum += amount
3✔
2586
                }
3✔
2587

2588
                // Finally check against the defined fee threshold.
2589
                if localSum > s.cfg.MaxFeeExposure {
3✔
UNCOV
2590
                        return true
×
UNCOV
2591
                }
×
2592
        }
2593

2594
        // Also check if the htlc is dust on the remote commitment, if we've
2595
        // reached this point.
2596
        if isRemoteDust {
6✔
2597
                remoteSum := link.getDustSum(
3✔
2598
                        lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
3✔
2599
                )
3✔
2600
                remoteSum += remoteMailDust
3✔
2601

3✔
2602
                // Optionally include the HTLC amount only for outgoing
3✔
2603
                // HTLCs.
3✔
2604
                if !incoming {
6✔
2605
                        remoteSum += amount
3✔
2606
                }
3✔
2607

2608
                // Finally check against the defined fee threshold.
2609
                if remoteSum > s.cfg.MaxFeeExposure {
3✔
2610
                        return true
×
2611
                }
×
2612
        }
2613

2614
        // If we reached this point, this HTLC is fine to forward.
2615
        return false
3✔
2616
}
2617

2618
// failMailboxUpdate is passed to the mailbox orchestrator which in turn passes
2619
// it to individual mailboxes. It allows the mailboxes to construct a
2620
// FailureMessage when failing back HTLC's due to expiry and may include an
2621
// alias in the ShortChannelID field. The outgoingScid is the SCID originally
2622
// used in the onion. The mailboxScid is the SCID that the mailbox and link
2623
// use. The mailboxScid is only used in the non-alias case, so it is always
2624
// the confirmed SCID.
2625
func (s *Switch) failMailboxUpdate(outgoingScid,
2626
        mailboxScid lnwire.ShortChannelID) lnwire.FailureMessage {
3✔
2627

3✔
2628
        // Try to use the failAliasUpdate function in case this is a channel
3✔
2629
        // that uses aliases. If it returns nil, we'll fallback to the original
3✔
2630
        // pre-alias behavior.
3✔
2631
        update := s.failAliasUpdate(outgoingScid, false)
3✔
2632
        if update == nil {
6✔
2633
                // Execute the fallback behavior.
3✔
2634
                var err error
3✔
2635
                update, err = s.cfg.FetchLastChannelUpdate(mailboxScid)
3✔
2636
                if err != nil {
3✔
2637
                        return &lnwire.FailTemporaryNodeFailure{}
×
2638
                }
×
2639
        }
2640

2641
        return lnwire.NewTemporaryChannelFailure(update)
3✔
2642
}
2643

2644
// failAliasUpdate prepares a ChannelUpdate for a failed incoming or outgoing
2645
// HTLC on a channel where the option-scid-alias feature bit was negotiated. If
2646
// the associated channel is not one of these, this function will return nil
2647
// and the caller is expected to handle this properly. In this case, a return
2648
// to the original non-alias behavior is expected.
2649
func (s *Switch) failAliasUpdate(scid lnwire.ShortChannelID,
2650
        incoming bool) *lnwire.ChannelUpdate1 {
3✔
2651

3✔
2652
        // This function does not defer the unlocking because of the database
3✔
2653
        // lookups for ChannelUpdate.
3✔
2654
        s.indexMtx.RLock()
3✔
2655

3✔
2656
        if s.cfg.IsAlias(scid) {
6✔
2657
                // The alias SCID was used. In the incoming case this means
3✔
2658
                // the channel is zero-conf as the link sets the scid. In the
3✔
2659
                // outgoing case, the sender set the scid to use and may be
3✔
2660
                // either the alias or the confirmed one, if it exists.
3✔
2661
                realScid, ok := s.aliasToReal[scid]
3✔
2662
                if !ok {
3✔
2663
                        // The real, confirmed SCID does not exist yet. Find
×
2664
                        // the "base" SCID that the link uses via the
×
2665
                        // baseIndex. If we can't find it, return nil. This
×
2666
                        // means the channel is zero-conf.
×
2667
                        baseScid, ok := s.baseIndex[scid]
×
2668
                        s.indexMtx.RUnlock()
×
2669
                        if !ok {
×
2670
                                return nil
×
2671
                        }
×
2672

2673
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2674
                        if err != nil {
×
2675
                                return nil
×
2676
                        }
×
2677

2678
                        // Replace the baseScid with the passed-in alias.
2679
                        update.ShortChannelID = scid
×
2680
                        sig, err := s.cfg.SignAliasUpdate(update)
×
2681
                        if err != nil {
×
2682
                                return nil
×
2683
                        }
×
2684

2685
                        update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2686
                        if err != nil {
×
2687
                                return nil
×
2688
                        }
×
2689

2690
                        return update
×
2691
                }
2692

2693
                s.indexMtx.RUnlock()
3✔
2694

3✔
2695
                // Fetch the SCID via the confirmed SCID and replace it with
3✔
2696
                // the alias.
3✔
2697
                update, err := s.cfg.FetchLastChannelUpdate(realScid)
3✔
2698
                if err != nil {
6✔
2699
                        return nil
3✔
2700
                }
3✔
2701

2702
                // In the incoming case, we want to ensure that we don't leak
2703
                // the UTXO in case the channel is private. In the outgoing
2704
                // case, since the alias was used, we do the same thing.
2705
                update.ShortChannelID = scid
3✔
2706
                sig, err := s.cfg.SignAliasUpdate(update)
3✔
2707
                if err != nil {
3✔
2708
                        return nil
×
2709
                }
×
2710

2711
                update.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
2712
                if err != nil {
3✔
2713
                        return nil
×
2714
                }
×
2715

2716
                return update
3✔
2717
        }
2718

2719
        // If the confirmed SCID is not in baseIndex, this is not an
2720
        // option-scid-alias or zero-conf channel.
2721
        baseScid, ok := s.baseIndex[scid]
3✔
2722
        if !ok {
6✔
2723
                s.indexMtx.RUnlock()
3✔
2724
                return nil
3✔
2725
        }
3✔
2726

2727
        // Fetch the link so we can get an alias to use in the ShortChannelID
2728
        // of the ChannelUpdate.
UNCOV
2729
        link, ok := s.forwardingIndex[baseScid]
×
UNCOV
2730
        s.indexMtx.RUnlock()
×
UNCOV
2731
        if !ok {
×
2732
                // This should never happen, but if it does for some reason,
×
2733
                // fallback to the old behavior.
×
2734
                return nil
×
2735
        }
×
2736

UNCOV
2737
        aliases := link.getAliases()
×
UNCOV
2738
        if len(aliases) == 0 {
×
2739
                // This should never happen, but if it does, fallback.
×
2740
                return nil
×
2741
        }
×
2742

2743
        // Fetch the ChannelUpdate via the real, confirmed SCID.
UNCOV
2744
        update, err := s.cfg.FetchLastChannelUpdate(scid)
×
UNCOV
2745
        if err != nil {
×
2746
                return nil
×
2747
        }
×
2748

2749
        // The incoming case will replace the ShortChannelID in the retrieved
2750
        // ChannelUpdate with the alias to ensure no privacy leak occurs. This
2751
        // would happen if a private non-zero-conf option-scid-alias
2752
        // feature-bit channel leaked its UTXO here rather than supplying an
2753
        // alias. In the outgoing case, the confirmed SCID was actually used
2754
        // for forwarding in the onion, so no replacement is necessary as the
2755
        // sender knows the scid.
UNCOV
2756
        if incoming {
×
UNCOV
2757
                // We will replace and sign the update with the first alias.
×
UNCOV
2758
                // Since this happens on the incoming side, it's not actually
×
UNCOV
2759
                // possible to know what the sender used in the onion.
×
UNCOV
2760
                update.ShortChannelID = aliases[0]
×
UNCOV
2761
                sig, err := s.cfg.SignAliasUpdate(update)
×
UNCOV
2762
                if err != nil {
×
2763
                        return nil
×
2764
                }
×
2765

UNCOV
2766
                update.Signature, err = lnwire.NewSigFromSignature(sig)
×
UNCOV
2767
                if err != nil {
×
2768
                        return nil
×
2769
                }
×
2770
        }
2771

UNCOV
2772
        return update
×
2773
}
2774

2775
// AddAliasForLink instructs the Switch to update its in-memory maps to reflect
2776
// that a link has a new alias.
2777
func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
2778
        alias lnwire.ShortChannelID) error {
×
2779

×
2780
        // Fetch the link so that we can update the underlying channel's set of
×
2781
        // aliases.
×
2782
        s.indexMtx.RLock()
×
2783
        link, err := s.getLink(chanID)
×
2784
        s.indexMtx.RUnlock()
×
2785
        if err != nil {
×
2786
                return err
×
2787
        }
×
2788

2789
        // If the link is a channel where the option-scid-alias feature bit was
2790
        // not negotiated, we'll return an error.
2791
        if !link.negotiatedAliasFeature() {
×
2792
                return fmt.Errorf("attempted to update non-alias channel")
×
2793
        }
×
2794

2795
        linkScid := link.ShortChanID()
×
2796

×
2797
        // We'll update the maps so the Switch includes this alias in its
×
2798
        // forwarding decisions.
×
2799
        if link.isZeroConf() {
×
2800
                if link.zeroConfConfirmed() {
×
2801
                        // If the channel has confirmed on-chain, we'll
×
2802
                        // add this alias to the aliasToReal map.
×
2803
                        confirmedScid := link.confirmedScid()
×
2804

×
2805
                        s.aliasToReal[alias] = confirmedScid
×
2806
                }
×
2807

2808
                // Add this alias to the baseIndex mapping.
2809
                s.baseIndex[alias] = linkScid
×
2810
        } else if link.negotiatedAliasFeature() {
×
2811
                // The channel is confirmed, so we'll populate the aliasToReal
×
2812
                // and baseIndex maps.
×
2813
                s.aliasToReal[alias] = linkScid
×
2814
                s.baseIndex[alias] = linkScid
×
2815
        }
×
2816

2817
        return nil
×
2818
}
2819

2820
// handlePacketAdd handles forwarding an Add packet.
2821
func (s *Switch) handlePacketAdd(packet *htlcPacket,
2822
        htlc *lnwire.UpdateAddHTLC) error {
3✔
2823

3✔
2824
        // Check if the node is set to reject all onward HTLCs and also make
3✔
2825
        // sure that HTLC is not from the source node.
3✔
2826
        if s.cfg.RejectHTLC {
6✔
2827
                failure := NewDetailedLinkError(
3✔
2828
                        &lnwire.FailChannelDisabled{},
3✔
2829
                        OutgoingFailureForwardsDisabled,
3✔
2830
                )
3✔
2831

3✔
2832
                return s.failAddPacket(packet, failure)
3✔
2833
        }
3✔
2834

2835
        // Before we attempt to find a non-strict forwarding path for this
2836
        // htlc, check whether the htlc is being routed over the same incoming
2837
        // and outgoing channel. If our node does not allow forwards of this
2838
        // nature, we fail the htlc early. This check is in place to disallow
2839
        // inefficiently routed htlcs from locking up our balance. With
2840
        // channels where the option-scid-alias feature was negotiated, we also
2841
        // have to be sure that the IDs aren't the same since one or both could
2842
        // be an alias.
2843
        linkErr := s.checkCircularForward(
3✔
2844
                packet.incomingChanID, packet.outgoingChanID,
3✔
2845
                s.cfg.AllowCircularRoute, htlc.PaymentHash,
3✔
2846
        )
3✔
2847
        if linkErr != nil {
3✔
UNCOV
2848
                return s.failAddPacket(packet, linkErr)
×
UNCOV
2849
        }
×
2850

2851
        s.indexMtx.RLock()
3✔
2852
        targetLink, err := s.getLinkByMapping(packet)
3✔
2853
        if err != nil {
6✔
2854
                s.indexMtx.RUnlock()
3✔
2855

3✔
2856
                log.Debugf("unable to find link with "+
3✔
2857
                        "destination %v", packet.outgoingChanID)
3✔
2858

3✔
2859
                // If packet was forwarded from another channel link than we
3✔
2860
                // should notify this link that some error occurred.
3✔
2861
                linkError := NewLinkError(
3✔
2862
                        &lnwire.FailUnknownNextPeer{},
3✔
2863
                )
3✔
2864

3✔
2865
                return s.failAddPacket(packet, linkError)
3✔
2866
        }
3✔
2867
        targetPeerKey := targetLink.PeerPubKey()
3✔
2868
        interfaceLinks, _ := s.getLinks(targetPeerKey)
3✔
2869
        s.indexMtx.RUnlock()
3✔
2870

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

3✔
2877
        // Find all destination channel links with appropriate bandwidth.
3✔
2878
        var destinations []ChannelLink
3✔
2879
        for _, link := range interfaceLinks {
6✔
2880
                var failure *LinkError
3✔
2881

3✔
2882
                // We'll skip any links that aren't yet eligible for
3✔
2883
                // forwarding.
3✔
2884
                if !link.EligibleToForward() {
3✔
UNCOV
2885
                        failure = NewDetailedLinkError(
×
UNCOV
2886
                                &lnwire.FailUnknownNextPeer{},
×
UNCOV
2887
                                OutgoingFailureLinkNotEligible,
×
UNCOV
2888
                        )
×
2889
                } else {
3✔
2890
                        // We'll ensure that the HTLC satisfies the current
3✔
2891
                        // forwarding conditions of this target link.
3✔
2892
                        currentHeight := atomic.LoadUint32(&s.bestHeight)
3✔
2893
                        failure = link.CheckHtlcForward(
3✔
2894
                                htlc.PaymentHash, packet.incomingAmount,
3✔
2895
                                packet.amount, packet.incomingTimeout,
3✔
2896
                                packet.outgoingTimeout, packet.inboundFee,
3✔
2897
                                currentHeight, packet.originalOutgoingChanID,
3✔
2898
                                htlc.CustomRecords,
3✔
2899
                        )
3✔
2900
                }
3✔
2901

2902
                // If this link can forward the htlc, add it to the set of
2903
                // destinations.
2904
                if failure == nil {
6✔
2905
                        destinations = append(destinations, link)
3✔
2906
                        continue
3✔
2907
                }
2908

2909
                linkErrs[link.ShortChanID()] = failure
3✔
2910
        }
2911

2912
        // If we had a forwarding failure due to the HTLC not satisfying the
2913
        // current policy, then we'll send back an error, but ensure we send
2914
        // back the error sourced at the *target* link.
2915
        if len(destinations) == 0 {
6✔
2916
                // At this point, some or all of the links rejected the HTLC so
3✔
2917
                // we couldn't forward it. So we'll try to look up the error
3✔
2918
                // that came from the source.
3✔
2919
                linkErr, ok := linkErrs[packet.outgoingChanID]
3✔
2920
                if !ok {
3✔
2921
                        // If we can't find the error of the source, then we'll
×
2922
                        // return an unknown next peer, though this should
×
2923
                        // never happen.
×
2924
                        linkErr = NewLinkError(
×
2925
                                &lnwire.FailUnknownNextPeer{},
×
2926
                        )
×
2927
                        log.Warnf("unable to find err source for "+
×
2928
                                "outgoing_link=%v, errors=%v",
×
2929
                                packet.outgoingChanID,
×
2930
                                lnutils.SpewLogClosure(linkErrs))
×
2931
                }
×
2932

2933
                log.Tracef("incoming HTLC(%x) violated "+
3✔
2934
                        "target outgoing link (id=%v) policy: %v",
3✔
2935
                        htlc.PaymentHash[:], packet.outgoingChanID,
3✔
2936
                        linkErr)
3✔
2937

3✔
2938
                return s.failAddPacket(packet, linkErr)
3✔
2939
        }
2940

2941
        // Choose a random link out of the set of links that can forward this
2942
        // htlc. The reason for randomization is to evenly distribute the htlc
2943
        // load without making assumptions about what the best channel is.
2944
        //nolint:gosec
2945
        destination := destinations[rand.Intn(len(destinations))]
3✔
2946

3✔
2947
        // Retrieve the incoming link by its ShortChannelID. Note that the
3✔
2948
        // incomingChanID is never set to hop.Source here.
3✔
2949
        s.indexMtx.RLock()
3✔
2950
        incomingLink, err := s.getLinkByShortID(packet.incomingChanID)
3✔
2951
        s.indexMtx.RUnlock()
3✔
2952
        if err != nil {
3✔
2953
                // If we couldn't find the incoming link, we can't evaluate the
×
2954
                // incoming's exposure to dust, so we just fail the HTLC back.
×
2955
                linkErr := NewLinkError(
×
2956
                        &lnwire.FailTemporaryChannelFailure{},
×
2957
                )
×
2958

×
2959
                return s.failAddPacket(packet, linkErr)
×
2960
        }
×
2961

2962
        // Evaluate whether this HTLC would increase our fee exposure over the
2963
        // threshold on the incoming link. If it does, fail it backwards.
2964
        if s.dustExceedsFeeThreshold(
3✔
2965
                incomingLink, packet.incomingAmount, true,
3✔
2966
        ) {
3✔
2967
                // The incoming dust exceeds the threshold, so we fail the add
×
2968
                // back.
×
2969
                linkErr := NewLinkError(
×
2970
                        &lnwire.FailTemporaryChannelFailure{},
×
2971
                )
×
2972

×
2973
                return s.failAddPacket(packet, linkErr)
×
2974
        }
×
2975

2976
        // Also evaluate whether this HTLC would increase our fee exposure over
2977
        // the threshold on the destination link. If it does, fail it back.
2978
        if s.dustExceedsFeeThreshold(
3✔
2979
                destination, packet.amount, false,
3✔
2980
        ) {
3✔
UNCOV
2981
                // The outgoing dust exceeds the threshold, so we fail the add
×
UNCOV
2982
                // back.
×
UNCOV
2983
                linkErr := NewLinkError(
×
UNCOV
2984
                        &lnwire.FailTemporaryChannelFailure{},
×
UNCOV
2985
                )
×
UNCOV
2986

×
UNCOV
2987
                return s.failAddPacket(packet, linkErr)
×
UNCOV
2988
        }
×
2989

2990
        // Send the packet to the destination channel link which manages the
2991
        // channel.
2992
        packet.outgoingChanID = destination.ShortChanID()
3✔
2993

3✔
2994
        return destination.handleSwitchPacket(packet)
3✔
2995
}
2996

2997
// handlePacketSettle handles forwarding a settle packet.
2998
func (s *Switch) handlePacketSettle(packet *htlcPacket) error {
3✔
2999
        // If the source of this packet has not been set, use the circuit map
3✔
3000
        // to lookup the origin.
3✔
3001
        circuit, err := s.closeCircuit(packet)
3✔
3002

3✔
3003
        // If the circuit is in the process of closing, we will return a nil as
3✔
3004
        // there's another packet handling undergoing.
3✔
3005
        if errors.Is(err, ErrCircuitClosing) {
6✔
3006
                log.Debugf("Circuit is closing for packet=%v", packet)
3✔
3007
                return nil
3✔
3008
        }
3✔
3009

3010
        // Exit early if there's another error.
3011
        if err != nil {
3✔
3012
                return err
×
3013
        }
×
3014

3015
        // closeCircuit returns a nil circuit when a settle packet returns an
3016
        // ErrUnknownCircuit error upon the inner call to CloseCircuit.
3017
        //
3018
        // NOTE: We can only get a nil circuit when it has already been deleted
3019
        // and when `UpdateFulfillHTLC` is received. After which `RevokeAndAck`
3020
        // is received, which invokes `processRemoteSettleFails` in its link.
3021
        if circuit == nil {
6✔
3022
                log.Debugf("Circuit already closed for packet=%v", packet)
3✔
3023
                return nil
3✔
3024
        }
3✔
3025

3026
        localHTLC := packet.incomingChanID == hop.Source
3✔
3027

3✔
3028
        // If this is a locally initiated HTLC, we need to handle the packet by
3✔
3029
        // storing the network result.
3✔
3030
        //
3✔
3031
        // A blank IncomingChanID in a circuit indicates that it is a pending
3✔
3032
        // user-initiated payment.
3✔
3033
        //
3✔
3034
        // NOTE: `closeCircuit` modifies the state of `packet`.
3✔
3035
        if localHTLC {
6✔
3036
                // TODO(yy): remove the goroutine and send back the error here.
3✔
3037
                s.wg.Add(1)
3✔
3038
                go s.handleLocalResponse(packet)
3✔
3039

3✔
3040
                // If this is a locally initiated HTLC, there's no need to
3✔
3041
                // forward it so we exit.
3✔
3042
                return nil
3✔
3043
        }
3✔
3044

3045
        // If this is an HTLC settle, and it wasn't from a locally initiated
3046
        // HTLC, then we'll log a forwarding event so we can flush it to disk
3047
        // later.
3048
        if circuit.Outgoing != nil {
6✔
3049
                log.Infof("Forwarded HTLC(%x) of %v (fee: %v) "+
3✔
3050
                        "from IncomingChanID(%v) to OutgoingChanID(%v)",
3✔
3051
                        circuit.PaymentHash[:], circuit.OutgoingAmount,
3✔
3052
                        circuit.IncomingAmount-circuit.OutgoingAmount,
3✔
3053
                        circuit.Incoming.ChanID, circuit.Outgoing.ChanID)
3✔
3054

3✔
3055
                s.fwdEventMtx.Lock()
3✔
3056
                s.pendingFwdingEvents = append(
3✔
3057
                        s.pendingFwdingEvents,
3✔
3058
                        channeldb.ForwardingEvent{
3✔
3059
                                Timestamp:      time.Now(),
3✔
3060
                                IncomingChanID: circuit.Incoming.ChanID,
3✔
3061
                                OutgoingChanID: circuit.Outgoing.ChanID,
3✔
3062
                                AmtIn:          circuit.IncomingAmount,
3✔
3063
                                AmtOut:         circuit.OutgoingAmount,
3✔
3064
                        },
3✔
3065
                )
3✔
3066
                s.fwdEventMtx.Unlock()
3✔
3067
        }
3✔
3068

3069
        // Deliver this packet.
3070
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3071
}
3072

3073
// handlePacketFail handles forwarding a fail packet.
3074
func (s *Switch) handlePacketFail(packet *htlcPacket,
3075
        htlc *lnwire.UpdateFailHTLC) error {
3✔
3076

3✔
3077
        // If the source of this packet has not been set, use the circuit map
3✔
3078
        // to lookup the origin.
3✔
3079
        circuit, err := s.closeCircuit(packet)
3✔
3080
        if err != nil {
3✔
3081
                return err
×
3082
        }
×
3083

3084
        // If this is a locally initiated HTLC, we need to handle the packet by
3085
        // storing the network result.
3086
        //
3087
        // A blank IncomingChanID in a circuit indicates that it is a pending
3088
        // user-initiated payment.
3089
        //
3090
        // NOTE: `closeCircuit` modifies the state of `packet`.
3091
        if packet.incomingChanID == hop.Source {
6✔
3092
                // TODO(yy): remove the goroutine and send back the error here.
3✔
3093
                s.wg.Add(1)
3✔
3094
                go s.handleLocalResponse(packet)
3✔
3095

3✔
3096
                // If this is a locally initiated HTLC, there's no need to
3✔
3097
                // forward it so we exit.
3✔
3098
                return nil
3✔
3099
        }
3✔
3100

3101
        // Exit early if this hasSource is true. This flag is only set via
3102
        // mailbox's `FailAdd`. This method has two callsites,
3103
        // - the packet has timed out after `MailboxDeliveryTimeout`, defaults
3104
        //   to 1 min.
3105
        // - the HTLC fails the validation in `channel.AddHTLC`.
3106
        // In either case, the `Reason` field is populated. Thus there's no
3107
        // need to proceed and extract the failure reason below.
3108
        if packet.hasSource {
3✔
UNCOV
3109
                // Deliver this packet.
×
UNCOV
3110
                return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
×
UNCOV
3111
        }
×
3112

3113
        // HTLC resolutions and messages restored from disk don't have the
3114
        // obfuscator set from the original htlc add packet - set it here for
3115
        // use in blinded errors.
3116
        packet.obfuscator = circuit.ErrorEncrypter
3✔
3117

3✔
3118
        switch {
3✔
3119
        // No message to encrypt, locally sourced payment.
3120
        case circuit.ErrorEncrypter == nil:
×
3121
                // TODO(yy) further check this case as we shouldn't end up here
3122
                // as `isLocal` is already false.
3123

3124
        // If this is a resolution message, then we'll need to encrypt it as
3125
        // it's actually internally sourced.
3126
        case packet.isResolution:
3✔
3127
                var err error
3✔
3128
                // TODO(roasbeef): don't need to pass actually?
3✔
3129
                failure := &lnwire.FailPermanentChannelFailure{}
3✔
3130
                htlc.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
3✔
3131
                        failure,
3✔
3132
                )
3✔
3133
                if err != nil {
3✔
3134
                        err = fmt.Errorf("unable to obfuscate error: %w", err)
×
3135
                        log.Error(err)
×
3136
                }
×
3137

3138
        // Alternatively, if the remote party sends us an
3139
        // UpdateFailMalformedHTLC, then we'll need to convert this into a
3140
        // proper well formatted onion error as there's no HMAC currently.
3141
        case packet.convertedError:
3✔
3142
                log.Infof("Converting malformed HTLC error for circuit for "+
3✔
3143
                        "Circuit(%x: (%s, %d) <-> (%s, %d))",
3✔
3144
                        packet.circuit.PaymentHash,
3✔
3145
                        packet.incomingChanID, packet.incomingHTLCID,
3✔
3146
                        packet.outgoingChanID, packet.outgoingHTLCID)
3✔
3147

3✔
3148
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
3✔
3149
                        htlc.Reason,
3✔
3150
                )
3✔
3151

3152
        default:
3✔
3153
                // Otherwise, it's a forwarded error, so we'll perform a
3✔
3154
                // wrapper encryption as normal.
3✔
3155
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
3✔
3156
                        htlc.Reason,
3✔
3157
                )
3✔
3158
        }
3159

3160
        // Deliver this packet.
3161
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3162
}
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