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

lightningnetwork / lnd / 13035292482

29 Jan 2025 03:59PM UTC coverage: 49.3% (-9.5%) from 58.777%
13035292482

Pull #9456

github

mohamedawnallah
docs: update release-notes-0.19.0.md

In this commit, we warn users about the removal
of RPCs `SendToRoute`, `SendToRouteSync`, `SendPayment`,
and `SendPaymentSync` in the next release 0.20.
Pull Request #9456: lnrpc+docs: deprecate warning `SendToRoute`, `SendToRouteSync`, `SendPayment`, and `SendPaymentSync` in Release 0.19

100634 of 204126 relevant lines covered (49.3%)

1.54 hits per line

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

74.39
/htlcswitch/switch.go
1
package htlcswitch
2

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

12
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/btcsuite/btcd/wire"
15
        "github.com/davecgh/go-spew/spew"
16
        "github.com/lightningnetwork/lnd/chainntnfs"
17
        "github.com/lightningnetwork/lnd/channeldb"
18
        "github.com/lightningnetwork/lnd/clock"
19
        "github.com/lightningnetwork/lnd/contractcourt"
20
        "github.com/lightningnetwork/lnd/fn/v2"
21
        "github.com/lightningnetwork/lnd/graph/db/models"
22
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
23
        "github.com/lightningnetwork/lnd/kvdb"
24
        "github.com/lightningnetwork/lnd/lntypes"
25
        "github.com/lightningnetwork/lnd/lnutils"
26
        "github.com/lightningnetwork/lnd/lnwallet"
27
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
28
        "github.com/lightningnetwork/lnd/lnwire"
29
        "github.com/lightningnetwork/lnd/ticker"
30
)
31

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

144
        // DB is the database backend that will be used to back the switch's
145
        // persistent circuit map.
146
        DB kvdb.Backend
147

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

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

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

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

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

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

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

183
        // HtlcNotifier is an instance of a htlcNotifier which we will pipe htlc
184
        // events through.
185
        HtlcNotifier htlcNotifier
186

187
        // FwdEventTicker is a signal that instructs the htlcswitch to flush any
188
        // pending forwarding events.
189
        FwdEventTicker ticker.Ticker
190

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

195
        // AckEventTicker is a signal instructing the htlcswitch to ack any settle
196
        // fails in forwarding packages.
197
        AckEventTicker ticker.Ticker
198

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

203
        // RejectHTLC is a flag that instructs the htlcswitch to reject any
204
        // HTLCs that are not from the source hop.
205
        RejectHTLC bool
206

207
        // Clock is a time source for the switch.
208
        Clock clock.Clock
209

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

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

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

227
        // IsAlias returns whether or not a given SCID is an alias.
228
        IsAlias func(scid lnwire.ShortChannelID) bool
229
}
230

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

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

248
        wg   sync.WaitGroup
249
        quit chan struct{}
250

251
        // cfg is a copy of the configuration struct that the htlc switch
252
        // service was initialized with.
253
        cfg *Config
254

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

262
        // circuits is storage for payment circuits which are used to
263
        // forward the settle/fail htlc updates back to the add htlc initiator.
264
        circuits CircuitMap
265

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

271
        // indexMtx is a read/write mutex that protects the set of indexes
272
        // below.
273
        indexMtx sync.RWMutex
274

275
        // pendingLinkIndex holds links that have not had their final, live
276
        // short_chan_id assigned.
277
        pendingLinkIndex map[lnwire.ChannelID]ChannelLink
278

279
        // links is a map of channel id and channel link which manages
280
        // this channel.
281
        linkIndex map[lnwire.ChannelID]ChannelLink
282

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

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

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

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

311
        // chanCloseRequests is used to transfer the channel close request to
312
        // the channel close handler.
313
        chanCloseRequests chan *ChanClose
314

315
        // resolutionMsgs is the channel that all external contract resolution
316
        // messages will be sent over.
317
        resolutionMsgs chan *resolutionMsg
318

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

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

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

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

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

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

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

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

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

3✔
388
        s.aliasToReal = make(map[lnwire.ShortChannelID]lnwire.ShortChannelID)
3✔
389
        s.baseIndex = make(map[lnwire.ShortChannelID]lnwire.ShortChannelID)
3✔
390

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

3✔
398
        return s, nil
3✔
399
}
400

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

407
        errChan chan error
408
}
409

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

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

427
        select {
3✔
428
        case err := <-errChan:
3✔
429
                return err
3✔
430
        case <-s.quit:
×
431
                return ErrSwitchExiting
×
432
        }
433
}
434

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

443
        if !errors.Is(err, ErrPaymentIDNotFound) {
3✔
444
                return false, err
×
445
        }
×
446

447
        return false, nil
3✔
448
}
449

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

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

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

491
        resultChan := make(chan *PaymentResult, 1)
3✔
492

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

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

511
                log.Debugf("Received network result %T for attemptID=%v", n.msg,
3✔
512
                        attemptID)
3✔
513

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

529
        return resultChan, nil
3✔
530
}
531

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

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

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

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

3✔
577
                return linkErr
3✔
578
        }
3✔
579

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

×
600
                return errFeeExposureExceeded
×
601
        }
×
602

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

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

615
        case len(actions.Fails) == 1:
×
616
                return ErrLocalAddFailed
×
617
        }
618

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

3✔
623
        return link.handleSwitchPacket(packet)
3✔
624
}
625

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

3✔
635
        log.Tracef("Updating link policies: %v", lnutils.SpewLogClosure(
3✔
636
                chanPolicies))
3✔
637

3✔
638
        s.indexMtx.RLock()
3✔
639

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

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

651
                link.UpdateForwardingPolicy(policy)
3✔
652
        }
653

654
        s.indexMtx.RUnlock()
3✔
655
}
656

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

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

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

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

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

3✔
689
        // No packets, nothing to do.
3✔
690
        if len(packets) == 0 {
6✔
691
                return nil
3✔
692
        }
3✔
693

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

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

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

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

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

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

762
                case len(actions.Drops) > 0 && packet.circuit == actions.Drops[0]:
3✔
763
                        actions.Drops = actions.Drops[1:]
3✔
764

765
                case len(actions.Fails) > 0 && packet.circuit == actions.Fails[0]:
×
766
                        failedPackets = append(failedPackets, packet)
×
767
                        actions.Fails = actions.Fails[1:]
×
768
                }
769
        }
770

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

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

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

808
                linkError := NewDetailedLinkError(
×
809
                        failure, OutgoingFailureIncompleteForward,
×
810
                )
×
811

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

819
        return nil
3✔
820
}
821

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

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

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

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

3✔
855
        command := &plexPacket{
3✔
856
                pkt: packet,
3✔
857
                err: errChan,
3✔
858
        }
3✔
859

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

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

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

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

904
        if !link.EligibleToForward() {
3✔
905
                log.Errorf("Link %v is not available to forward",
×
906
                        pkt.outgoingChanID)
×
907

×
908
                // The update does not need to be populated as the error
×
909
                // will be returned back to the router.
×
910
                return nil, NewDetailedLinkError(
×
911
                        lnwire.NewTemporaryChannelFailure(nil),
×
912
                        OutgoingFailureLinkNotEligible,
×
913
                )
×
914
        }
×
915

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

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

3✔
945
        attemptID := pkt.incomingHTLCID
3✔
946

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

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

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

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

992
        // Finally, notify on the htlc failure or success that has been handled.
993
        key := newHtlcKey(pkt)
3✔
994
        eventType := getEventType(pkt)
3✔
995

3✔
996
        switch htlc := pkt.htlc.(type) {
3✔
997
        case *lnwire.UpdateFulfillHTLC:
3✔
998
                s.cfg.HtlcNotifier.NotifySettleEvent(key, htlc.PaymentPreimage,
3✔
999
                        eventType)
3✔
1000

1001
        case *lnwire.UpdateFailHTLC:
3✔
1002
                s.cfg.HtlcNotifier.NotifyForwardingFailEvent(key, eventType)
3✔
1003
        }
1004
}
1005

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

3✔
1011
        switch htlc := n.msg.(type) {
3✔
1012

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

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

3✔
1030
                return &PaymentResult{
3✔
1031
                        Error: paymentErr,
3✔
1032
                }, nil
3✔
1033

1034
        default:
×
1035
                return nil, fmt.Errorf("received unknown response type: %T",
×
1036
                        htlc)
×
1037
        }
1038
}
1039

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

3✔
1051
        switch {
3✔
1052

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

×
1070
                        log.Errorf("%v: (hash=%v, pid=%d): %v",
×
1071
                                linkError.FailureDetail.FailureString(),
×
1072
                                paymentHash, attemptID, err)
×
1073

×
1074
                        return linkError
×
1075
                }
×
1076

1077
                // If we successfully decoded the failure reason, return it.
1078
                return NewLinkError(failureMsg)
3✔
1079

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

3✔
1090
                log.Infof("%v: hash=%v, pid=%d",
3✔
1091
                        linkError.FailureDetail.FailureString(),
3✔
1092
                        paymentHash, attemptID)
3✔
1093

3✔
1094
                return linkError
3✔
1095

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

×
1107
                        return ErrUnreadableFailureMessage
×
1108
                }
×
1109

1110
                return failure
3✔
1111
        }
1112
}
1113

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

1125
        case *lnwire.UpdateFulfillHTLC:
3✔
1126
                return s.handlePacketSettle(packet)
3✔
1127

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

1137
        default:
×
1138
                return fmt.Errorf("wrong update type: %T", htlc)
×
1139
        }
1140
}
1141

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

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

1158
                // Otherwise, we'll return a temporary channel failure.
1159
                return NewDetailedLinkError(
×
1160
                        lnwire.NewTemporaryChannelFailure(nil),
×
1161
                        OutgoingFailureCircularRoute,
×
1162
                )
×
1163
        }
1164

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

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

3✔
1186
        // Check base SCID equality.
3✔
1187
        if incomingBaseScid != outgoingBaseScid {
6✔
1188
                // The base SCIDs are not equal so these are not the same
3✔
1189
                // channel.
3✔
1190
                return nil
3✔
1191
        }
3✔
1192

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

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

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

1227
        log.Error(failure.Error())
3✔
1228

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

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

1260
        return failure
3✔
1261
}
1262

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

1275
                // Circuit successfully closed.
1276
                case nil:
3✔
1277
                        return circuit, nil
3✔
1278

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

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

1292
                // Unexpected error.
1293
                default:
×
1294
                        return nil, err
×
1295
                }
1296
        }
1297

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

1303
        // Open circuit successfully closed.
1304
        case nil:
3✔
1305
                pkt.incomingChanID = circuit.Incoming.ChanID
3✔
1306
                pkt.incomingHTLCID = circuit.Incoming.HtlcID
3✔
1307
                pkt.circuit = circuit
3✔
1308
                pkt.sourceRef = &circuit.AddRef
3✔
1309

3✔
1310
                pktType := "SETTLE"
3✔
1311
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
6✔
1312
                        pktType = "FAIL"
3✔
1313
                }
3✔
1314

1315
                log.Debugf("Closed completed %s circuit for %x: "+
3✔
1316
                        "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
3✔
1317
                        pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1318
                        pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1319

3✔
1320
                return circuit, nil
3✔
1321

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

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

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

×
1348
                        return nil, err
×
1349
                }
×
1350

1351
                return nil, nil
3✔
1352

1353
        // Unexpected error.
1354
        default:
×
1355
                return nil, err
×
1356
        }
1357
}
1358

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

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

1382
        var paymentHash lntypes.Hash
3✔
1383

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

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

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

×
1401
                return err
×
1402
        }
×
1403

1404
        log.Debugf("Closed %s circuit for %v: (%s, %d) <-> (%s, %d)", pktType,
3✔
1405
                paymentHash, pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1406
                pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1407

3✔
1408
        return nil
3✔
1409
}
1410

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

3✔
1421
        // TODO(roasbeef) abstract out the close updates.
3✔
1422
        updateChan := make(chan interface{}, 2)
3✔
1423
        errChan := make(chan error, 1)
3✔
1424

3✔
1425
        command := &ChanClose{
3✔
1426
                CloseType:      closeType,
3✔
1427
                ChanPoint:      chanPoint,
3✔
1428
                Updates:        updateChan,
3✔
1429
                TargetFeePerKw: targetFeePerKw,
3✔
1430
                MaxFee:         maxFee,
3✔
1431
                DeliveryScript: deliveryScript,
3✔
1432
                Err:            errChan,
3✔
1433
        }
3✔
1434

3✔
1435
        select {
3✔
1436
        case s.chanCloseRequests <- command:
3✔
1437
                return updateChan, errChan
3✔
1438

1439
        case <-s.quit:
×
1440
                errChan <- ErrSwitchExiting
×
1441
                close(updateChan)
×
1442
                return updateChan, errChan
×
1443
        }
1444
}
1445

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

3✔
1459
        defer func() {
6✔
1460
                s.blockEpochStream.Cancel()
3✔
1461

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

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

3✔
1495
                                l.Stop()
3✔
1496
                        }(link)
3✔
1497
                }
1498
                wg.Wait()
3✔
1499

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

1508
        // TODO(roasbeef): cleared vs settled distinction
1509
        var (
3✔
1510
                totalNumUpdates uint64
3✔
1511
                totalSatSent    btcutil.Amount
3✔
1512
                totalSatRecv    btcutil.Amount
3✔
1513
        )
3✔
1514
        s.cfg.LogEventTicker.Resume()
3✔
1515
        defer s.cfg.LogEventTicker.Stop()
3✔
1516

3✔
1517
        // Every 15 seconds, we'll flush out the forwarding events that
3✔
1518
        // occurred during that period.
3✔
1519
        s.cfg.FwdEventTicker.Resume()
3✔
1520
        defer s.cfg.FwdEventTicker.Stop()
3✔
1521

3✔
1522
        defer s.cfg.AckEventTicker.Stop()
3✔
1523

3✔
1524
out:
3✔
1525
        for {
6✔
1526

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

1533
                select {
3✔
1534
                case blockEpoch, ok := <-s.blockEpochStream.Epochs:
3✔
1535
                        if !ok {
3✔
1536
                                break out
×
1537
                        }
1538

1539
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
3✔
1540

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

3✔
1547
                        s.indexMtx.RLock()
3✔
1548
                        link, ok := s.linkIndex[chanID]
3✔
1549
                        if !ok {
6✔
1550
                                s.indexMtx.RUnlock()
3✔
1551

3✔
1552
                                req.Err <- fmt.Errorf("no peer for channel with "+
3✔
1553
                                        "chan_id=%x", chanID[:])
3✔
1554
                                continue
3✔
1555
                        }
1556
                        s.indexMtx.RUnlock()
3✔
1557

3✔
1558
                        peerPub := link.PeerPubKey()
3✔
1559
                        log.Debugf("Requesting local channel close: peer=%v, "+
3✔
1560
                                "chan_id=%x", link.PeerPubKey(), chanID[:])
3✔
1561

3✔
1562
                        go s.cfg.LocalChannelClose(peerPub[:], req)
3✔
1563

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

1581
                        // At this point, the resolution message has been
1582
                        // persisted. It is safe to signal success by sending
1583
                        // a nil error since the Switch will re-deliver the
1584
                        // resolution message on restart.
1585
                        resolutionMsg.errChan <- nil
3✔
1586

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

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

1609
                        log.Debugf("Received outside contract resolution, "+
3✔
1610
                                "mapping to: %v", spew.Sdump(pkt))
3✔
1611

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

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

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

3✔
1635
                                if err := s.FlushForwardingEvents(); err != nil {
3✔
1636
                                        log.Errorf("Unable to flush "+
×
1637
                                                "forwarding events: %v", err)
×
1638
                                }
×
1639
                        }()
1640

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

3✔
1651
                        var (
3✔
1652
                                newNumUpdates uint64
3✔
1653
                                newSatSent    btcutil.Amount
3✔
1654
                                newSatRecv    btcutil.Amount
3✔
1655
                        )
3✔
1656

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

3✔
1670
                        var (
3✔
1671
                                diffNumUpdates uint64
3✔
1672
                                diffSatSent    btcutil.Amount
3✔
1673
                                diffSatRecv    btcutil.Amount
3✔
1674
                        )
3✔
1675

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

1689
                        // If the diff of num updates is zero, then we haven't
1690
                        // forwarded anything in the last 10 seconds, so we can
1691
                        // skip this update.
1692
                        if diffNumUpdates == 0 {
6✔
1693
                                continue
3✔
1694
                        }
1695

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

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

3✔
1714
                        totalNumUpdates += diffNumUpdates
3✔
1715
                        totalSatSent += diffSatSent
3✔
1716
                        totalSatRecv += diffSatRecv
3✔
1717

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

1728
                        // Batch ack the settle/fail entries.
1729
                        if err := s.ackSettleFail(s.pendingSettleFails...); err != nil {
3✔
1730
                                log.Errorf("Unable to ack batch of settle/fails: %v", err)
×
1731
                                continue
×
1732
                        }
1733

1734
                        log.Tracef("Acked %d settle fails: %v",
3✔
1735
                                len(s.pendingSettleFails),
3✔
1736
                                lnutils.SpewLogClosure(s.pendingSettleFails))
3✔
1737

3✔
1738
                        // Reset the pendingSettleFails buffer while keeping acquired
3✔
1739
                        // memory.
3✔
1740
                        s.pendingSettleFails = s.pendingSettleFails[:0]
3✔
1741

1742
                case <-s.quit:
3✔
1743
                        return
3✔
1744
                }
1745
        }
1746
}
1747

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

1755
        log.Infof("HTLC Switch starting")
3✔
1756

3✔
1757
        blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
1758
        if err != nil {
3✔
1759
                return err
×
1760
        }
×
1761
        s.blockEpochStream = blockEpochStream
3✔
1762

3✔
1763
        s.wg.Add(1)
3✔
1764
        go s.htlcForwarder()
3✔
1765

3✔
1766
        if err := s.reforwardResponses(); err != nil {
3✔
1767
                s.Stop()
×
1768
                log.Errorf("unable to reforward responses: %v", err)
×
1769
                return err
×
1770
        }
×
1771

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

1779
        return nil
3✔
1780
}
1781

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

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

3✔
1802
                if s.circuits.LookupOpenCircuit(outKey) == nil {
6✔
1803
                        // The open circuit doesn't exist.
3✔
1804
                        err := s.resMsgStore.deleteResolutionMsg(&outKey)
3✔
1805
                        if err != nil {
3✔
1806
                                return err
×
1807
                        }
×
1808

1809
                        continue
3✔
1810
                }
1811

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

3✔
1822
                if resMsg.Failure != nil {
6✔
1823
                        resPkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1824
                } else {
3✔
1825
                        resPkt.htlc = &lnwire.UpdateFulfillHTLC{
×
1826
                                PaymentPreimage: *resMsg.PreImage,
×
1827
                        }
×
1828
                }
×
1829

1830
                switchPackets = append(switchPackets, resPkt)
3✔
1831
        }
1832

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

1840
        return nil
3✔
1841
}
1842

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

1854
        for _, openChannel := range openChannels {
6✔
1855
                shortChanID := openChannel.ShortChanID()
3✔
1856

3✔
1857
                // Locally-initiated payments never need reforwarding.
3✔
1858
                if shortChanID == hop.Source {
6✔
1859
                        continue
3✔
1860
                }
1861

1862
                // If the channel is pending, it should have no forwarding
1863
                // packages, and nothing to reforward.
1864
                if openChannel.IsPending {
3✔
1865
                        continue
×
1866
                }
1867

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

1881
                s.reforwardSettleFails(fwdPkgs)
3✔
1882
        }
1883

1884
        return nil
3✔
1885
}
1886

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

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

1904
        return fwdPkgs, nil
3✔
1905
}
1906

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

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

3✔
1939
                                // Add the packet to the batch to be forwarded, and
3✔
1940
                                // notify the overflow queue that a spare spot has been
3✔
1941
                                // freed up within the commitment state.
3✔
1942
                                switchPackets = append(switchPackets, settlePacket)
3✔
1943

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

×
1966
                                // Add the packet to the batch to be forwarded, and
×
1967
                                // notify the overflow queue that a spare spot has been
×
1968
                                // freed up within the commitment state.
×
1969
                                switchPackets = append(switchPackets, failPacket)
×
1970
                        }
1971
                }
1972

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

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

1991
        log.Info("HTLC Switch shutting down...")
3✔
1992
        defer log.Debug("HTLC Switch shutdown complete")
3✔
1993

3✔
1994
        close(s.quit)
3✔
1995

3✔
1996
        s.wg.Wait()
3✔
1997

3✔
1998
        // Wait until all active goroutines have finished exiting before
3✔
1999
        // stopping the mailboxes, otherwise the mailbox map could still be
3✔
2000
        // accessed and modified.
3✔
2001
        s.mailOrchestrator.Stop()
3✔
2002

3✔
2003
        return nil
3✔
2004
}
2005

2006
// CreateAndAddLink will create a link and then add it to the internal maps
2007
// when given a ChannelLinkConfig and LightningChannel.
2008
func (s *Switch) CreateAndAddLink(linkCfg ChannelLinkConfig,
2009
        lnChan *lnwallet.LightningChannel) error {
3✔
2010

3✔
2011
        link := NewChannelLink(linkCfg, lnChan)
3✔
2012
        return s.AddLink(link)
3✔
2013
}
3✔
2014

2015
// AddLink is used to initiate the handling of the add link command. The
2016
// request will be propagated and handled in the main goroutine.
2017
func (s *Switch) AddLink(link ChannelLink) error {
3✔
2018
        s.indexMtx.Lock()
3✔
2019
        defer s.indexMtx.Unlock()
3✔
2020

3✔
2021
        chanID := link.ChanID()
3✔
2022

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

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

3✔
2037
        // Attach the Switch's failAliasUpdate function to the link.
3✔
2038
        link.attachFailAliasUpdate(s.failAliasUpdate)
3✔
2039

3✔
2040
        if err := link.Start(); err != nil {
3✔
2041
                log.Errorf("AddLink failed to start link with chanID=%v: %v",
×
2042
                        chanID, err)
×
2043
                s.removeLink(chanID)
×
2044
                return err
×
2045
        }
×
2046

2047
        if shortChanID == hop.Source {
6✔
2048
                log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
3✔
2049
                        chanID, shortChanID)
3✔
2050

3✔
2051
                s.pendingLinkIndex[chanID] = link
3✔
2052
        } else {
6✔
2053
                log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
3✔
2054
                        chanID, shortChanID)
3✔
2055

3✔
2056
                s.addLiveLink(link)
3✔
2057
                s.mailOrchestrator.BindLiveShortChanID(
3✔
2058
                        mailbox, chanID, shortChanID,
3✔
2059
                )
3✔
2060
        }
3✔
2061

2062
        return nil
3✔
2063
}
2064

2065
// addLiveLink adds a link to all associated forwarding index, this makes it a
2066
// candidate for forwarding HTLCs.
2067
func (s *Switch) addLiveLink(link ChannelLink) {
3✔
2068
        linkScid := link.ShortChanID()
3✔
2069

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

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

3✔
2085
        s.updateLinkAliases(link)
3✔
2086
}
2087

2088
// UpdateLinkAliases is the externally exposed wrapper for updating link
2089
// aliases. It acquires the indexMtx and calls the internal method.
2090
func (s *Switch) UpdateLinkAliases(link ChannelLink) {
3✔
2091
        s.indexMtx.Lock()
3✔
2092
        defer s.indexMtx.Unlock()
3✔
2093

3✔
2094
        s.updateLinkAliases(link)
3✔
2095
}
3✔
2096

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

3✔
2105
        aliases := link.getAliases()
3✔
2106
        if link.isZeroConf() {
6✔
2107
                if link.zeroConfConfirmed() {
6✔
2108
                        // Since the zero-conf channel has confirmed, we can
3✔
2109
                        // populate the aliasToReal mapping.
3✔
2110
                        confirmedScid := link.confirmedScid()
3✔
2111

3✔
2112
                        for _, alias := range aliases {
6✔
2113
                                s.aliasToReal[alias] = confirmedScid
3✔
2114
                        }
3✔
2115

2116
                        // Add the confirmed SCID as a key in the baseIndex.
2117
                        s.baseIndex[confirmedScid] = linkScid
3✔
2118
                }
2119

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

2138
                for alias, real := range s.baseIndex {
6✔
2139
                        if real == linkScid {
6✔
2140
                                delete(s.baseIndex, alias)
3✔
2141
                        }
3✔
2142
                }
2143

2144
                // The link's SCID is the confirmed SCID for non-zero-conf
2145
                // option-scid-alias feature bit channels.
2146
                for _, alias := range aliases {
6✔
2147
                        s.aliasToReal[alias] = linkScid
3✔
2148
                        s.baseIndex[alias] = linkScid
3✔
2149
                }
3✔
2150

2151
                // Since the link's SCID is confirmed, it was not included in
2152
                // the baseIndex above as a key. Add it now.
2153
                s.baseIndex[linkScid] = linkScid
3✔
2154
        }
2155
}
2156

2157
// GetLink is used to initiate the handling of the get link command. The
2158
// request will be propagated/handled to/in the main goroutine.
2159
func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelUpdateHandler,
2160
        error) {
3✔
2161

3✔
2162
        s.indexMtx.RLock()
3✔
2163
        defer s.indexMtx.RUnlock()
3✔
2164

3✔
2165
        return s.getLink(chanID)
3✔
2166
}
3✔
2167

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

2179
        return link, nil
3✔
2180
}
2181

2182
// GetLinkByShortID attempts to return the link which possesses the target short
2183
// channel ID.
2184
func (s *Switch) GetLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink,
2185
        error) {
3✔
2186

3✔
2187
        s.indexMtx.RLock()
3✔
2188
        defer s.indexMtx.RUnlock()
3✔
2189

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

2200
                // An alias was found, use it to lookup if a link exists.
2201
                return s.getLinkByShortID(aliasID)
3✔
2202
        }
2203

2204
        return link, nil
3✔
2205
}
2206

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

2217
        return link, nil
3✔
2218
}
2219

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

3✔
2241
        // Set the originalOutgoingChanID so the proper channel_update can be
3✔
2242
        // sent back if the option-scid-alias feature bit was negotiated.
3✔
2243
        pkt.originalOutgoingChanID = chanID
3✔
2244

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

2254
                // A mapping exists, so use baseScid to find the link in the
2255
                // forwardingIndex.
2256
                link, ok := s.forwardingIndex[baseScid]
3✔
2257
                if !ok {
3✔
2258
                        // Link not found, bail.
×
2259
                        return nil, ErrChannelLinkNotFound
×
2260
                }
×
2261

2262
                // Change the packet's outgoingChanID field so that errors are
2263
                // properly attributed.
2264
                pkt.outgoingChanID = baseScid
3✔
2265

3✔
2266
                // Return the link without checking if it's private or not.
3✔
2267
                return link, nil
3✔
2268
        }
2269

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

2283
                return link, nil
3✔
2284
        }
2285

2286
        // Fetch the link whose internal SCID is baseScid.
2287
        link, ok := s.forwardingIndex[baseScid]
3✔
2288
        if !ok {
3✔
2289
                // Link wasn't found, bail out.
×
2290
                return nil, ErrChannelLinkNotFound
×
2291
        }
×
2292

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

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

2307
// HasActiveLink returns true if the given channel ID has a link in the link
2308
// index AND the link is eligible to forward.
2309
func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
3✔
2310
        s.indexMtx.RLock()
3✔
2311
        defer s.indexMtx.RUnlock()
3✔
2312

3✔
2313
        if link, ok := s.linkIndex[chanID]; ok {
6✔
2314
                return link.EligibleToForward()
3✔
2315
        }
3✔
2316

2317
        return false
3✔
2318
}
2319

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

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

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

2357
        // Stop the link before removing it from the maps.
2358
        link.Stop()
3✔
2359

3✔
2360
        s.indexMtx.Lock()
3✔
2361
        _ = s.removeLink(chanID)
3✔
2362

3✔
2363
        // Close stopChan and remove this link from the linkStopIndex.
3✔
2364
        // Deleting from the index and removing from the link must be done
3✔
2365
        // in the same block while the mutex is held.
3✔
2366
        close(stopChan)
3✔
2367
        delete(s.linkStopIndex, chanID)
3✔
2368
        s.indexMtx.Unlock()
3✔
2369
}
2370

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

3✔
2377
        link, err := s.getLink(chanID)
3✔
2378
        if err != nil {
3✔
2379
                return nil
×
2380
        }
×
2381

2382
        // Remove the channel from live link indexes.
2383
        delete(s.pendingLinkIndex, link.ChanID())
3✔
2384
        delete(s.linkIndex, link.ChanID())
3✔
2385
        delete(s.forwardingIndex, link.ShortChanID())
3✔
2386

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

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

2400
        return link
3✔
2401
}
2402

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

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

2417
        // Try to update the link's underlying channel state, returning early
2418
        // if this update failed.
2419
        _, err := link.UpdateShortChanID()
3✔
2420
        if err != nil {
3✔
2421
                return err
×
2422
        }
×
2423

2424
        // Since the zero-conf channel is confirmed, we should populate the
2425
        // aliasToReal map and update the baseIndex.
2426
        aliases := link.getAliases()
3✔
2427

3✔
2428
        confirmedScid := link.confirmedScid()
3✔
2429

3✔
2430
        for _, alias := range aliases {
6✔
2431
                s.aliasToReal[alias] = confirmedScid
3✔
2432
        }
3✔
2433

2434
        s.baseIndex[confirmedScid] = link.ShortChanID()
3✔
2435

3✔
2436
        return nil
3✔
2437
}
2438

2439
// GetLinksByInterface fetches all the links connected to a particular node
2440
// identified by the serialized compressed form of its public key.
2441
func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
2442
        error) {
3✔
2443

3✔
2444
        s.indexMtx.RLock()
3✔
2445
        defer s.indexMtx.RUnlock()
3✔
2446

3✔
2447
        var handlers []ChannelUpdateHandler
3✔
2448

3✔
2449
        links, err := s.getLinks(hop)
3✔
2450
        if err != nil {
6✔
2451
                return nil, err
3✔
2452
        }
3✔
2453

2454
        // Range over the returned []ChannelLink to convert them into
2455
        // []ChannelUpdateHandler.
2456
        for _, link := range links {
6✔
2457
                handlers = append(handlers, link)
3✔
2458
        }
3✔
2459

2460
        return handlers, nil
3✔
2461
}
2462

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

2473
        channelLinks := make([]ChannelLink, 0, len(links))
3✔
2474
        for _, link := range links {
6✔
2475
                channelLinks = append(channelLinks, link)
3✔
2476
        }
3✔
2477

2478
        return channelLinks, nil
3✔
2479
}
2480

2481
// CircuitModifier returns a reference to subset of the interfaces provided by
2482
// the circuit map, to allow links to open and close circuits.
2483
func (s *Switch) CircuitModifier() CircuitModifier {
3✔
2484
        return s.circuits
3✔
2485
}
3✔
2486

2487
// CircuitLookup returns a reference to subset of the interfaces provided by the
2488
// circuit map, to allow looking up circuits.
2489
func (s *Switch) CircuitLookup() CircuitLookup {
3✔
2490
        return s.circuits
3✔
2491
}
3✔
2492

2493
// commitCircuits persistently adds a circuit to the switch's circuit map.
2494
func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
2495
        *CircuitFwdActions, error) {
×
2496

×
2497
        return s.circuits.CommitCircuits(circuits...)
×
2498
}
×
2499

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

3✔
2509
        // If we won't have any forwarding events, then we can exit early.
3✔
2510
        if len(s.pendingFwdingEvents) == 0 {
6✔
2511
                s.fwdEventMtx.Unlock()
3✔
2512
                return nil
3✔
2513
        }
3✔
2514

2515
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
3✔
2516
        copy(events[:], s.pendingFwdingEvents[:])
3✔
2517

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

3✔
2524
        // Finally, we'll write out the copied events to the persistent
3✔
2525
        // forwarding log.
3✔
2526
        return s.cfg.FwdingLog.AddForwardingEvents(events)
3✔
2527
}
2528

2529
// BestHeight returns the best height known to the switch.
2530
func (s *Switch) BestHeight() uint32 {
3✔
2531
        return atomic.LoadUint32(&s.bestHeight)
3✔
2532
}
3✔
2533

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

3✔
2545
        // Retrieve the link's current commitment feerate and dustClosure.
3✔
2546
        feeRate := link.getFeeRate()
3✔
2547
        isDust := link.getDustClosure()
3✔
2548

3✔
2549
        // Evaluate if the HTLC is dust on either sides' commitment.
3✔
2550
        isLocalDust := isDust(
3✔
2551
                feeRate, incoming, lntypes.Local, amount.ToSatoshis(),
3✔
2552
        )
3✔
2553
        isRemoteDust := isDust(
3✔
2554
                feeRate, incoming, lntypes.Remote, amount.ToSatoshis(),
3✔
2555
        )
3✔
2556

3✔
2557
        if !(isLocalDust || isRemoteDust) {
6✔
2558
                // If the HTLC is not dust on either commitment, it's fine to
3✔
2559
                // forward.
3✔
2560
                return false
3✔
2561
        }
3✔
2562

2563
        // Fetch the dust sums currently in the mailbox for this link.
2564
        cid := link.ChanID()
3✔
2565
        sid := link.ShortChanID()
3✔
2566
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
3✔
2567
        localMailDust, remoteMailDust := mailbox.DustPackets()
3✔
2568

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

3✔
2577
                // Optionally include the HTLC amount only for outgoing
3✔
2578
                // HTLCs.
3✔
2579
                if !incoming {
6✔
2580
                        localSum += amount
3✔
2581
                }
3✔
2582

2583
                // Finally check against the defined fee threshold.
2584
                if localSum > s.cfg.MaxFeeExposure {
3✔
2585
                        return true
×
2586
                }
×
2587
        }
2588

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

3✔
2597
                // Optionally include the HTLC amount only for outgoing
3✔
2598
                // HTLCs.
3✔
2599
                if !incoming {
6✔
2600
                        remoteSum += amount
3✔
2601
                }
3✔
2602

2603
                // Finally check against the defined fee threshold.
2604
                if remoteSum > s.cfg.MaxFeeExposure {
3✔
2605
                        return true
×
2606
                }
×
2607
        }
2608

2609
        // If we reached this point, this HTLC is fine to forward.
2610
        return false
3✔
2611
}
2612

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

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

2636
        return lnwire.NewTemporaryChannelFailure(update)
3✔
2637
}
2638

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

3✔
2647
        // This function does not defer the unlocking because of the database
3✔
2648
        // lookups for ChannelUpdate.
3✔
2649
        s.indexMtx.RLock()
3✔
2650

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

2668
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2669
                        if err != nil {
×
2670
                                return nil
×
2671
                        }
×
2672

2673
                        // Replace the baseScid with the passed-in alias.
2674
                        update.ShortChannelID = scid
×
2675
                        sig, err := s.cfg.SignAliasUpdate(update)
×
2676
                        if err != nil {
×
2677
                                return nil
×
2678
                        }
×
2679

2680
                        update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2681
                        if err != nil {
×
2682
                                return nil
×
2683
                        }
×
2684

2685
                        return update
×
2686
                }
2687

2688
                s.indexMtx.RUnlock()
3✔
2689

3✔
2690
                // Fetch the SCID via the confirmed SCID and replace it with
3✔
2691
                // the alias.
3✔
2692
                update, err := s.cfg.FetchLastChannelUpdate(realScid)
3✔
2693
                if err != nil {
6✔
2694
                        return nil
3✔
2695
                }
3✔
2696

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

2706
                update.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
2707
                if err != nil {
3✔
2708
                        return nil
×
2709
                }
×
2710

2711
                return update
3✔
2712
        }
2713

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

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

2732
        aliases := link.getAliases()
×
2733
        if len(aliases) == 0 {
×
2734
                // This should never happen, but if it does, fallback.
×
2735
                return nil
×
2736
        }
×
2737

2738
        // Fetch the ChannelUpdate via the real, confirmed SCID.
2739
        update, err := s.cfg.FetchLastChannelUpdate(scid)
×
2740
        if err != nil {
×
2741
                return nil
×
2742
        }
×
2743

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

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

2767
        return update
×
2768
}
2769

2770
// AddAliasForLink instructs the Switch to update its in-memory maps to reflect
2771
// that a link has a new alias.
2772
func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
2773
        alias lnwire.ShortChannelID) error {
×
2774

×
2775
        // Fetch the link so that we can update the underlying channel's set of
×
2776
        // aliases.
×
2777
        s.indexMtx.RLock()
×
2778
        link, err := s.getLink(chanID)
×
2779
        s.indexMtx.RUnlock()
×
2780
        if err != nil {
×
2781
                return err
×
2782
        }
×
2783

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

2790
        linkScid := link.ShortChanID()
×
2791

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

×
2800
                        s.aliasToReal[alias] = confirmedScid
×
2801
                }
×
2802

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

2812
        return nil
×
2813
}
2814

2815
// handlePacketAdd handles forwarding an Add packet.
2816
func (s *Switch) handlePacketAdd(packet *htlcPacket,
2817
        htlc *lnwire.UpdateAddHTLC) error {
3✔
2818

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

3✔
2827
                return s.failAddPacket(packet, failure)
3✔
2828
        }
3✔
2829

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

2846
        s.indexMtx.RLock()
3✔
2847
        targetLink, err := s.getLinkByMapping(packet)
3✔
2848
        if err != nil {
6✔
2849
                s.indexMtx.RUnlock()
3✔
2850

3✔
2851
                log.Debugf("unable to find link with "+
3✔
2852
                        "destination %v", packet.outgoingChanID)
3✔
2853

3✔
2854
                // If packet was forwarded from another channel link than we
3✔
2855
                // should notify this link that some error occurred.
3✔
2856
                linkError := NewLinkError(
3✔
2857
                        &lnwire.FailUnknownNextPeer{},
3✔
2858
                )
3✔
2859

3✔
2860
                return s.failAddPacket(packet, linkError)
3✔
2861
        }
3✔
2862
        targetPeerKey := targetLink.PeerPubKey()
3✔
2863
        interfaceLinks, _ := s.getLinks(targetPeerKey)
3✔
2864
        s.indexMtx.RUnlock()
3✔
2865

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

3✔
2872
        // Find all destination channel links with appropriate bandwidth.
3✔
2873
        var destinations []ChannelLink
3✔
2874
        for _, link := range interfaceLinks {
6✔
2875
                var failure *LinkError
3✔
2876

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

2897
                // If this link can forward the htlc, add it to the set of
2898
                // destinations.
2899
                if failure == nil {
6✔
2900
                        destinations = append(destinations, link)
3✔
2901
                        continue
3✔
2902
                }
2903

2904
                linkErrs[link.ShortChanID()] = failure
3✔
2905
        }
2906

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

2928
                log.Tracef("incoming HTLC(%x) violated "+
3✔
2929
                        "target outgoing link (id=%v) policy: %v",
3✔
2930
                        htlc.PaymentHash[:], packet.outgoingChanID,
3✔
2931
                        linkErr)
3✔
2932

3✔
2933
                return s.failAddPacket(packet, linkErr)
3✔
2934
        }
2935

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

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

×
2954
                return s.failAddPacket(packet, linkErr)
×
2955
        }
×
2956

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

×
2968
                return s.failAddPacket(packet, linkErr)
×
2969
        }
×
2970

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

×
2982
                return s.failAddPacket(packet, linkErr)
×
2983
        }
×
2984

2985
        // Send the packet to the destination channel link which manages the
2986
        // channel.
2987
        packet.outgoingChanID = destination.ShortChanID()
3✔
2988

3✔
2989
        return destination.handleSwitchPacket(packet)
3✔
2990
}
2991

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

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

3005
        // Exit early if there's another error.
3006
        if err != nil {
3✔
3007
                return err
×
3008
        }
×
3009

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

3021
        localHTLC := packet.incomingChanID == hop.Source
3✔
3022

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

3✔
3035
                // If this is a locally initiated HTLC, there's no need to
3✔
3036
                // forward it so we exit.
3✔
3037
                return nil
3✔
3038
        }
3✔
3039

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

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

3064
        // Deliver this packet.
3065
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3066
}
3067

3068
// handlePacketFail handles forwarding a fail packet.
3069
func (s *Switch) handlePacketFail(packet *htlcPacket,
3070
        htlc *lnwire.UpdateFailHTLC) error {
3✔
3071

3✔
3072
        // If the source of this packet has not been set, use the circuit map
3✔
3073
        // to lookup the origin.
3✔
3074
        circuit, err := s.closeCircuit(packet)
3✔
3075
        if err != nil {
3✔
3076
                return err
×
3077
        }
×
3078

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

3✔
3091
                // If this is a locally initiated HTLC, there's no need to
3✔
3092
                // forward it so we exit.
3✔
3093
                return nil
3✔
3094
        }
3✔
3095

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

3108
        // HTLC resolutions and messages restored from disk don't have the
3109
        // obfuscator set from the original htlc add packet - set it here for
3110
        // use in blinded errors.
3111
        packet.obfuscator = circuit.ErrorEncrypter
3✔
3112

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

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

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

3✔
3143
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
3✔
3144
                        htlc.Reason,
3✔
3145
                )
3✔
3146

3147
        default:
3✔
3148
                // Otherwise, it's a forwarded error, so we'll perform a
3✔
3149
                // wrapper encryption as normal.
3✔
3150
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
3✔
3151
                        htlc.Reason,
3✔
3152
                )
3✔
3153
        }
3154

3155
        // Deliver this packet.
3156
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3157
}
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