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

lightningnetwork / lnd / 12165272839

04 Dec 2024 05:35PM UTC coverage: 58.978% (+0.2%) from 58.789%
12165272839

Pull #9316

github

ziggie1984
docs: add release-notes.
Pull Request #9316: routing: fix mc blinded path behaviour.

125 of 130 new or added lines in 4 files covered. (96.15%)

55 existing lines in 9 files now uncovered.

133554 of 226448 relevant lines covered (58.98%)

19570.84 hits per line

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

83.21
/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"
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) {
345✔
358
        resStore := newResolutionStore(cfg.DB)
345✔
359

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

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

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

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

345✔
398
        return s, nil
345✔
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 {
5✔
416
        errChan := make(chan error, 1)
5✔
417

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

427
        select {
5✔
428
        case err := <-errChan:
5✔
429
                return err
5✔
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) {
4✔
438
        _, err := s.networkResults.getResult(attemptID)
4✔
439
        if err == nil {
4✔
440
                return true, nil
×
441
        }
×
442

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

447
        return false, nil
4✔
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) {
311✔
461

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

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

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

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

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

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

305✔
514
                // Extract the result and pass it to the result channel.
305✔
515
                result, err := s.extractResult(
305✔
516
                        deobfuscator, n, attemptID, paymentHash,
305✔
517
                )
305✔
518
                if err != nil {
305✔
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
305✔
527
        }()
528

529
        return resultChan, nil
309✔
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 {
4✔
537
        return s.networkResults.cleanStore(keepPids)
4✔
538
}
4✔
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 {
420✔
546

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

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

8✔
577
                return linkErr
8✔
578
        }
8✔
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) {
417✔
583
                // Notify the htlc notifier of a link failure on our outgoing
1✔
584
                // link. We use the FailTemporaryChannelFailure in place of a
1✔
585
                // more descriptive error message.
1✔
586
                linkErr := NewLinkError(
1✔
587
                        &lnwire.FailTemporaryChannelFailure{},
1✔
588
                )
1✔
589
                s.cfg.HtlcNotifier.NotifyLinkFailEvent(
1✔
590
                        newHtlcKey(packet),
1✔
591
                        HtlcInfo{
1✔
592
                                OutgoingTimeLock: htlc.Expiry,
1✔
593
                                OutgoingAmt:      htlc.Amount,
1✔
594
                        },
1✔
595
                        HtlcEventTypeSend,
1✔
596
                        linkErr,
1✔
597
                        false,
1✔
598
                )
1✔
599

1✔
600
                return errFeeExposureExceeded
1✔
601
        }
1✔
602

603
        circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
415✔
604
        actions, err := s.circuits.CommitCircuits(circuit)
415✔
605
        if err != nil {
415✔
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 {
415✔
612
        case len(actions.Drops) == 1:
1✔
613
                return ErrDuplicateAdd
1✔
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
414✔
622

414✔
623
        return link.handleSwitchPacket(packet)
414✔
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) {
4✔
634

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

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

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

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

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

654
        s.indexMtx.RUnlock()
4✔
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 {
6✔
661

6✔
662
        circuit := s.circuits.LookupOpenCircuit(models.CircuitKey{
6✔
663
                ChanID: chanID,
6✔
664
                HtlcID: htlcIndex,
6✔
665
        })
6✔
666
        return circuit != nil && circuit.Incoming.ChanID != hop.Source
6✔
667
}
6✔
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 {
873✔
677

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

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

873✔
689
        // No packets, nothing to do.
873✔
690
        if len(packets) == 0 {
1,097✔
691
                return nil
224✔
692
        }
224✔
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
653✔
697
        wg.Add(1)
653✔
698
        defer wg.Done()
653✔
699

653✔
700
        // Before spawning the following goroutine to proxy our error responses,
653✔
701
        // check to see if we have already been issued a shutdown request. If
653✔
702
        // so, we exit early to avoid incrementing the switch's waitgroup while
653✔
703
        // it is already in the process of shutting down.
653✔
704
        select {
653✔
705
        case <-linkQuit:
1✔
706
                return nil
1✔
707
        case <-s.quit:
1✔
708
                return nil
1✔
709
        default:
652✔
710
                // Spawn a goroutine to log the errors returned from failed packets.
652✔
711
                s.wg.Add(1)
652✔
712
                go s.logFwdErrs(&numSent, &wg, fwdChan)
652✔
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
652✔
719
        var addBatch []*htlcPacket
652✔
720
        for _, packet := range packets {
1,304✔
721
                switch htlc := packet.htlc.(type) {
652✔
722
                case *lnwire.UpdateAddHTLC:
91✔
723
                        circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
91✔
724
                        packet.circuit = circuit
91✔
725
                        circuits = append(circuits, circuit)
91✔
726
                        addBatch = append(addBatch, packet)
91✔
727
                default:
565✔
728
                        err := s.routeAsync(packet, fwdChan, linkQuit)
565✔
729
                        if err != nil {
575✔
730
                                return fmt.Errorf("failed to forward packet %w",
10✔
731
                                        err)
10✔
732
                        }
10✔
733
                        numSent++
540✔
734
                }
735
        }
736

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

743
        // Write any circuits that we found to disk.
744
        actions, err := s.circuits.CommitCircuits(circuits...)
91✔
745
        if err != nil {
91✔
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
91✔
756
        for _, packet := range addBatch {
182✔
757
                switch {
91✔
758
                case len(actions.Adds) > 0 && packet.circuit == actions.Adds[0]:
87✔
759
                        addedPackets = append(addedPackets, packet)
87✔
760
                        actions.Adds = actions.Adds[1:]
87✔
761

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

765
                case len(actions.Fails) > 0 && packet.circuit == actions.Fails[0]:
3✔
766
                        failedPackets = append(failedPackets, packet)
3✔
767
                        actions.Fails = actions.Fails[1:]
3✔
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 {
178✔
774
                err := s.routeAsync(packet, fwdChan, linkQuit)
87✔
775
                if err != nil {
88✔
776
                        return fmt.Errorf("failed to forward packet %w", err)
1✔
777
                }
1✔
778
                numSent++
86✔
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 {
93✔
785
                var failure lnwire.FailureMessage
3✔
786
                incomingID := failedPackets[0].incomingChanID
3✔
787

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

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

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

819
        return nil
90✔
820
}
821

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

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

652✔
831
        numSent := *num
652✔
832
        for i := 0; i < numSent; i++ {
1,274✔
833
                select {
622✔
834
                case err := <-fwdChan:
622✔
835
                        if err != nil {
649✔
836
                                log.Errorf("Unhandled error while reforwarding htlc "+
27✔
837
                                        "settle/fail over htlcswitch: %v", err)
27✔
838
                        }
27✔
UNCOV
839
                case <-s.quit:
×
UNCOV
840
                        log.Errorf("unable to forward htlc packet " +
×
UNCOV
841
                                "htlc switch was stopped")
×
UNCOV
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 {
648✔
854

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

648✔
860
        select {
648✔
861
        case s.htlcPlex <- command:
622✔
862
                return nil
622✔
863
        case <-linkQuit:
11✔
864
                return ErrLinkShuttingDown
11✔
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) {
420✔
875

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

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

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

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

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

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

308✔
944
        attemptID := pkt.incomingHTLCID
308✔
945

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

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

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

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

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

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

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

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

305✔
1010
        switch htlc := n.msg.(type) {
305✔
1011

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

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

128✔
1029
                return &PaymentResult{
128✔
1030
                        Error: paymentErr,
128✔
1031
                }, nil
128✔
1032

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

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

128✔
1050
        switch {
128✔
1051

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

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

×
1073
                        return linkError
×
1074
                }
×
1075

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

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

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

4✔
1093
                return linkError
4✔
1094

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

1✔
1106
                        return ErrUnreadableFailureMessage
1✔
1107
                }
1✔
1108

1109
                return failure
122✔
1110
        }
1111
}
1112

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

1124
        case *lnwire.UpdateFulfillHTLC:
403✔
1125
                return s.handlePacketSettle(packet)
403✔
1126

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

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

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

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

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

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

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

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

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

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

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

1226
        log.Error(failure.Error())
30✔
1227

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

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

1259
        return failure
30✔
1260
}
1261

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

1274
                // Circuit successfully closed.
1275
                case nil:
15✔
1276
                        return circuit, nil
15✔
1277

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

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

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

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

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

340✔
1309
                pktType := "SETTLE"
340✔
1310
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
471✔
1311
                        pktType = "FAIL"
131✔
1312
                }
131✔
1313

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

340✔
1319
                return circuit, nil
340✔
1320

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

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

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

4✔
1347
                        return nil, err
4✔
1348
                }
4✔
1349

1350
                return nil, nil
194✔
1351

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

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

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

1381
        var paymentHash lntypes.Hash
318✔
1382

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

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

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

×
1400
                return err
×
1401
        }
×
1402

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

318✔
1407
        return nil
318✔
1408
}
1409

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

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

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

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

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

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

211✔
1458
        defer func() {
422✔
1459
                s.blockEpochStream.Cancel()
211✔
1460

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

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

297✔
1494
                                l.Stop()
297✔
1495
                        }(link)
297✔
1496
                }
1497
                wg.Wait()
211✔
1498

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

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

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

211✔
1521
        defer s.cfg.AckEventTicker.Stop()
211✔
1522

211✔
1523
out:
211✔
1524
        for {
1,047✔
1525

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

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

1538
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
4✔
1539

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

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

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

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

4✔
1561
                        go s.cfg.LocalChannelClose(peerPub[:], req)
4✔
1562

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

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

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

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

1608
                        log.Infof("Received outside contract resolution, "+
5✔
1609
                                "mapping to: %v", spew.Sdump(pkt))
5✔
1610

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

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

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

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

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

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

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

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

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

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

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

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

6✔
1713
                        totalNumUpdates += diffNumUpdates
6✔
1714
                        totalSatSent += diffSatSent
6✔
1715
                        totalSatRecv += diffSatRecv
6✔
1716

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

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

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

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

1741
                case <-s.quit:
211✔
1742
                        return
211✔
1743
                }
1744
        }
1745
}
1746

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

1754
        log.Infof("HTLC Switch starting")
211✔
1755

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

211✔
1762
        s.wg.Add(1)
211✔
1763
        go s.htlcForwarder()
211✔
1764

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

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

1778
        return nil
211✔
1779
}
1780

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

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

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

1808
                        continue
5✔
1809
                }
1810

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

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

1829
                switchPackets = append(switchPackets, resPkt)
4✔
1830
        }
1831

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

1839
        return nil
211✔
1840
}
1841

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

1853
        for _, openChannel := range openChannels {
344✔
1854
                shortChanID := openChannel.ShortChanID()
133✔
1855

133✔
1856
                // Locally-initiated payments never need reforwarding.
133✔
1857
                if shortChanID == hop.Source {
137✔
1858
                        continue
4✔
1859
                }
1860

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

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

1880
                s.reforwardSettleFails(fwdPkgs)
133✔
1881
        }
1882

1883
        return nil
211✔
1884
}
1885

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

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

1903
        return fwdPkgs, nil
133✔
1904
}
1905

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

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

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

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

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

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

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

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

313✔
1993
        close(s.quit)
313✔
1994

313✔
1995
        s.wg.Wait()
313✔
1996

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

313✔
2002
        return nil
313✔
2003
}
2004

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

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

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

340✔
2020
        chanID := link.ChanID()
340✔
2021

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

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

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

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

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

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

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

2061
        return nil
339✔
2062
}
2063

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

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

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

338✔
2084
        s.updateLinkAliases(link)
338✔
2085
}
2086

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

4✔
2093
        s.updateLinkAliases(link)
4✔
2094
}
4✔
2095

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

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

19✔
2111
                        for _, alias := range aliases {
45✔
2112
                                s.aliasToReal[alias] = confirmedScid
26✔
2113
                        }
26✔
2114

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

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

2137
                for alias, real := range s.baseIndex {
27✔
2138
                        if real == linkScid {
11✔
2139
                                delete(s.baseIndex, alias)
4✔
2140
                        }
4✔
2141
                }
2142

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

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

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

3,191✔
2161
        s.indexMtx.RLock()
3,191✔
2162
        defer s.indexMtx.RUnlock()
3,191✔
2163

3,191✔
2164
        return s.getLink(chanID)
3,191✔
2165
}
3,191✔
2166

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

2178
        return link, nil
3,521✔
2179
}
2180

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

4✔
2186
        s.indexMtx.RLock()
4✔
2187
        defer s.indexMtx.RUnlock()
4✔
2188

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

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

2203
        return link, nil
4✔
2204
}
2205

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

2216
        return link, nil
480✔
2217
}
2218

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

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

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

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

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

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

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

2282
                return link, nil
60✔
2283
        }
2284

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

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

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

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

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

2316
        return false
4✔
2317
}
2318

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

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

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

2356
        // Stop the link before removing it from the maps.
2357
        link.Stop()
22✔
2358

22✔
2359
        s.indexMtx.Lock()
22✔
2360
        _ = s.removeLink(chanID)
22✔
2361

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

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

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

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

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

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

2399
        return link
315✔
2400
}
2401

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

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

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

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

5✔
2427
        confirmedScid := link.confirmedScid()
5✔
2428

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

2433
        s.baseIndex[confirmedScid] = link.ShortChanID()
5✔
2434

5✔
2435
        return nil
5✔
2436
}
2437

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

4✔
2443
        s.indexMtx.RLock()
4✔
2444
        defer s.indexMtx.RUnlock()
4✔
2445

4✔
2446
        var handlers []ChannelUpdateHandler
4✔
2447

4✔
2448
        links, err := s.getLinks(hop)
4✔
2449
        if err != nil {
8✔
2450
                return nil, err
4✔
2451
        }
4✔
2452

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

2459
        return handlers, nil
4✔
2460
}
2461

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

2472
        channelLinks := make([]ChannelLink, 0, len(links))
80✔
2473
        for _, link := range links {
164✔
2474
                channelLinks = append(channelLinks, link)
84✔
2475
        }
84✔
2476

2477
        return channelLinks, nil
80✔
2478
}
2479

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

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

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

17✔
2496
        return s.circuits.CommitCircuits(circuits...)
17✔
2497
}
17✔
2498

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

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

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

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

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

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

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

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

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

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

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

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

404✔
2576
                // Optionally include the HTLC amount only for outgoing
404✔
2577
                // HTLCs.
404✔
2578
                if !incoming {
768✔
2579
                        localSum += amount
364✔
2580
                }
364✔
2581

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

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

402✔
2596
                // Optionally include the HTLC amount only for outgoing
402✔
2597
                // HTLCs.
402✔
2598
                if !incoming {
764✔
2599
                        remoteSum += amount
362✔
2600
                }
362✔
2601

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

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

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

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

2635
        return lnwire.NewTemporaryChannelFailure(update)
15✔
2636
}
2637

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

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

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

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

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

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

2684
                        return update
×
2685
                }
2686

2687
                s.indexMtx.RUnlock()
15✔
2688

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

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

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

2710
                return update
15✔
2711
        }
2712

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

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

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

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

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

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

2766
        return update
5✔
2767
}
2768

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

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

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

2789
        linkScid := link.ShortChanID()
×
2790

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

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

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

2811
        return nil
×
2812
}
2813

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

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

5✔
2826
                return s.failAddPacket(packet, failure)
5✔
2827
        }
5✔
2828

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

2845
        s.indexMtx.RLock()
84✔
2846
        targetLink, err := s.getLinkByMapping(packet)
84✔
2847
        if err != nil {
92✔
2848
                s.indexMtx.RUnlock()
8✔
2849

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

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

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

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

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

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

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

2904
                linkErrs[link.ShortChanID()] = failure
24✔
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 {
100✔
2911
                // At this point, some or all of the links rejected the HTLC so
20✔
2912
                // we couldn't forward it. So we'll try to look up the error
20✔
2913
                // that came from the source.
20✔
2914
                linkErr, ok := linkErrs[packet.outgoingChanID]
20✔
2915
                if !ok {
20✔
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 "+
20✔
2929
                        "target outgoing link (id=%v) policy: %v",
20✔
2930
                        htlc.PaymentHash[:], packet.outgoingChanID,
20✔
2931
                        linkErr)
20✔
2932

20✔
2933
                return s.failAddPacket(packet, linkErr)
20✔
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))]
64✔
2941

64✔
2942
        // Retrieve the incoming link by its ShortChannelID. Note that the
64✔
2943
        // incomingChanID is never set to hop.Source here.
64✔
2944
        s.indexMtx.RLock()
64✔
2945
        incomingLink, err := s.getLinkByShortID(packet.incomingChanID)
64✔
2946
        s.indexMtx.RUnlock()
64✔
2947
        if err != nil {
64✔
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(
64✔
2960
                incomingLink, packet.incomingAmount, true,
64✔
2961
        ) {
64✔
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(
64✔
2974
                destination, packet.amount, false,
64✔
2975
        ) {
65✔
2976
                // The outgoing dust exceeds the threshold, so we fail the add
1✔
2977
                // back.
1✔
2978
                linkErr := NewLinkError(
1✔
2979
                        &lnwire.FailTemporaryChannelFailure{},
1✔
2980
                )
1✔
2981

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

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

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

2992
// handlePacketSettle handles forwarding a settle packet.
2993
func (s *Switch) handlePacketSettle(packet *htlcPacket) error {
403✔
2994
        // If the source of this packet has not been set, use the circuit map
403✔
2995
        // to lookup the origin.
403✔
2996
        circuit, err := s.closeCircuit(packet)
403✔
2997
        if err != nil {
407✔
2998
                return err
4✔
2999
        }
4✔
3000

3001
        // closeCircuit returns a nil circuit when a settle packet returns an
3002
        // ErrUnknownCircuit error upon the inner call to CloseCircuit.
3003
        //
3004
        // NOTE: We can only get a nil circuit when it has already been deleted
3005
        // and when `UpdateFulfillHTLC` is received. After which `RevokeAndAck`
3006
        // is received, which invokes `processRemoteSettleFails` in its link.
3007
        if circuit == nil {
597✔
3008
                log.Debugf("Found nil circuit: packet=%v", spew.Sdump(packet))
194✔
3009
                return nil
194✔
3010
        }
194✔
3011

3012
        localHTLC := packet.incomingChanID == hop.Source
213✔
3013

213✔
3014
        // If this is a locally initiated HTLC, we need to handle the packet by
213✔
3015
        // storing the network result.
213✔
3016
        //
213✔
3017
        // A blank IncomingChanID in a circuit indicates that it is a pending
213✔
3018
        // user-initiated payment.
213✔
3019
        //
213✔
3020
        // NOTE: `closeCircuit` modifies the state of `packet`.
213✔
3021
        if localHTLC {
397✔
3022
                // TODO(yy): remove the goroutine and send back the error here.
184✔
3023
                s.wg.Add(1)
184✔
3024
                go s.handleLocalResponse(packet)
184✔
3025

184✔
3026
                // If this is a locally initiated HTLC, there's no need to
184✔
3027
                // forward it so we exit.
184✔
3028
                return nil
184✔
3029
        }
184✔
3030

3031
        // If this is an HTLC settle, and it wasn't from a locally initiated
3032
        // HTLC, then we'll log a forwarding event so we can flush it to disk
3033
        // later.
3034
        if circuit.Outgoing != nil {
66✔
3035
                log.Infof("Forwarded HTLC(%x) of %v (fee: %v) "+
33✔
3036
                        "from IncomingChanID(%v) to OutgoingChanID(%v)",
33✔
3037
                        circuit.PaymentHash[:], circuit.OutgoingAmount,
33✔
3038
                        circuit.IncomingAmount-circuit.OutgoingAmount,
33✔
3039
                        circuit.Incoming.ChanID, circuit.Outgoing.ChanID)
33✔
3040

33✔
3041
                s.fwdEventMtx.Lock()
33✔
3042
                s.pendingFwdingEvents = append(
33✔
3043
                        s.pendingFwdingEvents,
33✔
3044
                        channeldb.ForwardingEvent{
33✔
3045
                                Timestamp:      time.Now(),
33✔
3046
                                IncomingChanID: circuit.Incoming.ChanID,
33✔
3047
                                OutgoingChanID: circuit.Outgoing.ChanID,
33✔
3048
                                AmtIn:          circuit.IncomingAmount,
33✔
3049
                                AmtOut:         circuit.OutgoingAmount,
33✔
3050
                        },
33✔
3051
                )
33✔
3052
                s.fwdEventMtx.Unlock()
33✔
3053
        }
33✔
3054

3055
        // Deliver this packet.
3056
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
33✔
3057
}
3058

3059
// handlePacketFail handles forwarding a fail packet.
3060
func (s *Switch) handlePacketFail(packet *htlcPacket,
3061
        htlc *lnwire.UpdateFailHTLC) error {
142✔
3062

142✔
3063
        // If the source of this packet has not been set, use the circuit map
142✔
3064
        // to lookup the origin.
142✔
3065
        circuit, err := s.closeCircuit(packet)
142✔
3066
        if err != nil {
146✔
3067
                return err
4✔
3068
        }
4✔
3069

3070
        // If this is a locally initiated HTLC, we need to handle the packet by
3071
        // storing the network result.
3072
        //
3073
        // A blank IncomingChanID in a circuit indicates that it is a pending
3074
        // user-initiated payment.
3075
        //
3076
        // NOTE: `closeCircuit` modifies the state of `packet`.
3077
        if packet.incomingChanID == hop.Source {
270✔
3078
                // TODO(yy): remove the goroutine and send back the error here.
128✔
3079
                s.wg.Add(1)
128✔
3080
                go s.handleLocalResponse(packet)
128✔
3081

128✔
3082
                // If this is a locally initiated HTLC, there's no need to
128✔
3083
                // forward it so we exit.
128✔
3084
                return nil
128✔
3085
        }
128✔
3086

3087
        // Exit early if this hasSource is true. This flag is only set via
3088
        // mailbox's `FailAdd`. This method has two callsites,
3089
        // - the packet has timed out after `MailboxDeliveryTimeout`, defaults
3090
        //   to 1 min.
3091
        // - the HTLC fails the validation in `channel.AddHTLC`.
3092
        // In either case, the `Reason` field is populated. Thus there's no
3093
        // need to proceed and extract the failure reason below.
3094
        if packet.hasSource {
29✔
3095
                // Deliver this packet.
11✔
3096
                return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
11✔
3097
        }
11✔
3098

3099
        // HTLC resolutions and messages restored from disk don't have the
3100
        // obfuscator set from the original htlc add packet - set it here for
3101
        // use in blinded errors.
3102
        packet.obfuscator = circuit.ErrorEncrypter
11✔
3103

11✔
3104
        switch {
11✔
3105
        // No message to encrypt, locally sourced payment.
3106
        case circuit.ErrorEncrypter == nil:
×
3107
                // TODO(yy) further check this case as we shouldn't end up here
3108
                // as `isLocal` is already false.
3109

3110
        // If this is a resolution message, then we'll need to encrypt it as
3111
        // it's actually internally sourced.
3112
        case packet.isResolution:
4✔
3113
                var err error
4✔
3114
                // TODO(roasbeef): don't need to pass actually?
4✔
3115
                failure := &lnwire.FailPermanentChannelFailure{}
4✔
3116
                htlc.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
4✔
3117
                        failure,
4✔
3118
                )
4✔
3119
                if err != nil {
4✔
3120
                        err = fmt.Errorf("unable to obfuscate error: %w", err)
×
3121
                        log.Error(err)
×
3122
                }
×
3123

3124
        // Alternatively, if the remote party sends us an
3125
        // UpdateFailMalformedHTLC, then we'll need to convert this into a
3126
        // proper well formatted onion error as there's no HMAC currently.
3127
        case packet.convertedError:
6✔
3128
                log.Infof("Converting malformed HTLC error for circuit for "+
6✔
3129
                        "Circuit(%x: (%s, %d) <-> (%s, %d))",
6✔
3130
                        packet.circuit.PaymentHash,
6✔
3131
                        packet.incomingChanID, packet.incomingHTLCID,
6✔
3132
                        packet.outgoingChanID, packet.outgoingHTLCID)
6✔
3133

6✔
3134
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
6✔
3135
                        htlc.Reason,
6✔
3136
                )
6✔
3137

3138
        default:
9✔
3139
                // Otherwise, it's a forwarded error, so we'll perform a
9✔
3140
                // wrapper encryption as normal.
9✔
3141
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
9✔
3142
                        htlc.Reason,
9✔
3143
                )
9✔
3144
        }
3145

3146
        // Deliver this packet.
3147
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
11✔
3148
}
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