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

lightningnetwork / lnd / 15380904630

02 Jun 2025 12:07AM UTC coverage: 58.379% (+0.05%) from 58.327%
15380904630

Pull #9883

github

web-flow
Merge 4109ecb05 into bff2f2440
Pull Request #9883: protofsm: add thread-safe IsRunning method to StateMachine

1 of 6 new or added lines in 1 file covered. (16.67%)

19 existing lines in 6 files now uncovered.

97496 of 167006 relevant lines covered (58.38%)

1.81 hits per line

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

74.68
/htlcswitch/switch.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
        errChan chan error
412
}
413

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

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

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

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

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

451
        return false, nil
3✔
452
}
453

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

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

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

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

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

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

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

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

533
        return resultChan, nil
3✔
534
}
535

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

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

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

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

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

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

×
604
                return errFeeExposureExceeded
×
605
        }
×
606

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

823
        return nil
3✔
824
}
825

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1055
        switch {
3✔
1056

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

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

×
1078
                        return linkError
×
1079
                }
×
1080

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

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

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

3✔
1098
                return linkError
3✔
1099

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

×
1111
                        return ErrUnreadableFailureMessage
×
1112
                }
×
1113

1114
                return failure
3✔
1115
        }
1116
}
1117

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

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

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

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

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

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

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

1165
                // Otherwise, we'll return a temporary channel failure.
1166
                return NewDetailedLinkError(
×
1167
                        lnwire.NewTemporaryChannelFailure(nil),
×
1168
                        OutgoingFailureCircularRoute,
×
1169
                )
×
1170
        }
1171

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

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

3✔
1193
        // Check base SCID equality.
3✔
1194
        if incomingBaseScid != outgoingBaseScid {
6✔
1195
                log.Tracef("Incoming base SCID %v does not match outgoing "+
3✔
1196
                        "base SCID %v (payment hash: %x)", incomingBaseScid,
3✔
1197
                        outgoingBaseScid, paymentHash[:])
3✔
1198

3✔
1199
                // The base SCIDs are not equal so these are not the same
3✔
1200
                // channel.
3✔
1201
                return nil
3✔
1202
        }
3✔
1203

1204
        // If the incoming and outgoing link are equal, the htlc is part of a
1205
        // circular route which may be used to lock up our liquidity. If the
1206
        // switch is configured to allow circular routes, log that we are
1207
        // allowing the route then return nil.
1208
        if allowCircular {
×
1209
                log.Debugf("allowing circular route over link: %v "+
×
1210
                        "(payment hash: %x)", incoming, paymentHash)
×
1211
                return nil
×
1212
        }
×
1213

1214
        // If our node disallows circular routes, return a temporary channel
1215
        // failure. There is nothing wrong with the policy used by the remote
1216
        // node, so we do not include a channel update.
1217
        return NewDetailedLinkError(
×
1218
                lnwire.NewTemporaryChannelFailure(nil),
×
1219
                OutgoingFailureCircularRoute,
×
1220
        )
×
1221
}
1222

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

1238
        log.Error(failure.Error())
3✔
1239

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

3✔
1261
        // Route a fail packet back to the source link.
3✔
1262
        err = s.mailOrchestrator.Deliver(failPkt.incomingChanID, failPkt)
3✔
1263
        if err != nil {
3✔
1264
                err = fmt.Errorf("source chanid=%v unable to "+
×
1265
                        "handle switch packet: %v",
×
1266
                        packet.incomingChanID, err)
×
1267
                log.Error(err)
×
1268
                return err
×
1269
        }
×
1270

1271
        return failure
3✔
1272
}
1273

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

1286
                // Circuit successfully closed.
1287
                case nil:
3✔
1288
                        return circuit, nil
3✔
1289

1290
                // Circuit was previously closed, but has not been deleted.
1291
                // We'll just drop this response until the circuit has been
1292
                // fully removed.
1293
                case ErrCircuitClosing:
×
1294
                        return nil, err
×
1295

1296
                // Failed to close circuit because it does not exist. This is
1297
                // likely because the circuit was already successfully closed.
1298
                // Since this packet failed locally, there is no forwarding
1299
                // package entry to acknowledge.
1300
                case ErrUnknownCircuit:
×
1301
                        return nil, err
×
1302

1303
                // Unexpected error.
1304
                default:
×
1305
                        return nil, err
×
1306
                }
1307
        }
1308

1309
        // Otherwise, this is packet was received from the remote party.  Use
1310
        // circuit map to find the incoming link to receive the settle/fail.
1311
        circuit, err := s.circuits.CloseCircuit(pkt.outKey())
3✔
1312
        switch err {
3✔
1313

1314
        // Open circuit successfully closed.
1315
        case nil:
3✔
1316
                pkt.incomingChanID = circuit.Incoming.ChanID
3✔
1317
                pkt.incomingHTLCID = circuit.Incoming.HtlcID
3✔
1318
                pkt.circuit = circuit
3✔
1319
                pkt.sourceRef = &circuit.AddRef
3✔
1320

3✔
1321
                pktType := "SETTLE"
3✔
1322
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
6✔
1323
                        pktType = "FAIL"
3✔
1324
                }
3✔
1325

1326
                log.Debugf("Closed completed %s circuit for %x: "+
3✔
1327
                        "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
3✔
1328
                        pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1329
                        pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1330

3✔
1331
                return circuit, nil
3✔
1332

1333
        // Circuit was previously closed, but has not been deleted. We'll just
1334
        // drop this response until the circuit has been removed.
1335
        case ErrCircuitClosing:
3✔
1336
                return nil, err
3✔
1337

1338
        // Failed to close circuit because it does not exist. This is likely
1339
        // because the circuit was already successfully closed.
1340
        case ErrUnknownCircuit:
3✔
1341
                if pkt.destRef != nil {
6✔
1342
                        // Add this SettleFailRef to the set of pending settle/fail entries
3✔
1343
                        // awaiting acknowledgement.
3✔
1344
                        s.pendingSettleFails = append(s.pendingSettleFails, *pkt.destRef)
3✔
1345
                }
3✔
1346

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

×
1359
                        return nil, err
×
1360
                }
×
1361

1362
                return nil, nil
3✔
1363

1364
        // Unexpected error.
1365
        default:
×
1366
                return nil, err
×
1367
        }
1368
}
1369

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

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

1393
        var paymentHash lntypes.Hash
3✔
1394

3✔
1395
        // Perform a defensive check to make sure we don't try to access a nil
3✔
1396
        // circuit.
3✔
1397
        circuit := pkt.circuit
3✔
1398
        if circuit != nil {
6✔
1399
                copy(paymentHash[:], circuit.PaymentHash[:])
3✔
1400
        }
3✔
1401

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

3✔
1405
        err := s.circuits.DeleteCircuits(pkt.inKey())
3✔
1406
        if err != nil {
3✔
1407
                log.Warnf("Failed to tear down circuit (%s, %d) <-> (%s, %d) "+
×
1408
                        "with payment_hash=%v using %s pkt", pkt.incomingChanID,
×
1409
                        pkt.incomingHTLCID, pkt.outgoingChanID,
×
1410
                        pkt.outgoingHTLCID, pkt.circuit.PaymentHash, pktType)
×
1411

×
1412
                return err
×
1413
        }
×
1414

1415
        log.Debugf("Closed %s circuit for %v: (%s, %d) <-> (%s, %d)", pktType,
3✔
1416
                paymentHash, pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1417
                pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1418

3✔
1419
        return nil
3✔
1420
}
1421

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

3✔
1432
        // TODO(roasbeef) abstract out the close updates.
3✔
1433
        updateChan := make(chan interface{}, 2)
3✔
1434
        errChan := make(chan error, 1)
3✔
1435

3✔
1436
        command := &ChanClose{
3✔
1437
                CloseType:      closeType,
3✔
1438
                ChanPoint:      chanPoint,
3✔
1439
                Updates:        updateChan,
3✔
1440
                TargetFeePerKw: targetFeePerKw,
3✔
1441
                DeliveryScript: deliveryScript,
3✔
1442
                Err:            errChan,
3✔
1443
                MaxFee:         maxFee,
3✔
1444
                Ctx:            ctx,
3✔
1445
        }
3✔
1446

3✔
1447
        select {
3✔
1448
        case s.chanCloseRequests <- command:
3✔
1449
                return updateChan, errChan
3✔
1450

1451
        case <-s.quit:
×
1452
                errChan <- ErrSwitchExiting
×
1453
                close(updateChan)
×
1454
                return updateChan, errChan
×
1455
        }
1456
}
1457

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

3✔
1471
        defer func() {
6✔
1472
                s.blockEpochStream.Cancel()
3✔
1473

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

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

3✔
1507
                                l.Stop()
3✔
1508
                        }(link)
3✔
1509
                }
1510
                wg.Wait()
3✔
1511

3✔
1512
                // Before we exit fully, we'll attempt to flush out any
3✔
1513
                // forwarding events that may still be lingering since the last
3✔
1514
                // batch flush.
3✔
1515
                if err := s.FlushForwardingEvents(); err != nil {
3✔
1516
                        log.Errorf("unable to flush forwarding events: %v", err)
×
1517
                }
×
1518
        }()
1519

1520
        // TODO(roasbeef): cleared vs settled distinction
1521
        var (
3✔
1522
                totalNumUpdates uint64
3✔
1523
                totalSatSent    btcutil.Amount
3✔
1524
                totalSatRecv    btcutil.Amount
3✔
1525
        )
3✔
1526
        s.cfg.LogEventTicker.Resume()
3✔
1527
        defer s.cfg.LogEventTicker.Stop()
3✔
1528

3✔
1529
        // Every 15 seconds, we'll flush out the forwarding events that
3✔
1530
        // occurred during that period.
3✔
1531
        s.cfg.FwdEventTicker.Resume()
3✔
1532
        defer s.cfg.FwdEventTicker.Stop()
3✔
1533

3✔
1534
        defer s.cfg.AckEventTicker.Stop()
3✔
1535

3✔
1536
out:
3✔
1537
        for {
6✔
1538

3✔
1539
                // If the set of pending settle/fail entries is non-zero,
3✔
1540
                // reinstate the ack ticker so we can batch ack them.
3✔
1541
                if len(s.pendingSettleFails) > 0 {
6✔
1542
                        s.cfg.AckEventTicker.Resume()
3✔
1543
                }
3✔
1544

1545
                select {
3✔
1546
                case blockEpoch, ok := <-s.blockEpochStream.Epochs:
3✔
1547
                        if !ok {
3✔
1548
                                break out
×
1549
                        }
1550

1551
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
3✔
1552

1553
                // A local close request has arrived, we'll forward this to the
1554
                // relevant link (if it exists) so the channel can be
1555
                // cooperatively closed (if possible).
1556
                case req := <-s.chanCloseRequests:
3✔
1557
                        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
3✔
1558

3✔
1559
                        s.indexMtx.RLock()
3✔
1560
                        link, ok := s.linkIndex[chanID]
3✔
1561
                        if !ok {
6✔
1562
                                s.indexMtx.RUnlock()
3✔
1563

3✔
1564
                                req.Err <- fmt.Errorf("no peer for channel with "+
3✔
1565
                                        "chan_id=%x", chanID[:])
3✔
1566
                                continue
3✔
1567
                        }
1568
                        s.indexMtx.RUnlock()
3✔
1569

3✔
1570
                        peerPub := link.PeerPubKey()
3✔
1571
                        log.Debugf("Requesting local channel close: peer=%x, "+
3✔
1572
                                "chan_id=%x", link.PeerPubKey(), chanID[:])
3✔
1573

3✔
1574
                        go s.cfg.LocalChannelClose(peerPub[:], req)
3✔
1575

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

1593
                        // At this point, the resolution message has been
1594
                        // persisted. It is safe to signal success by sending
1595
                        // a nil error since the Switch will re-deliver the
1596
                        // resolution message on restart.
1597
                        resolutionMsg.errChan <- nil
3✔
1598

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

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

1621
                        log.Debugf("Received outside contract resolution, "+
3✔
1622
                                "mapping to: %v", spew.Sdump(pkt))
3✔
1623

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

1633
                // A new packet has arrived for forwarding, we'll interpret the
1634
                // packet concretely, then either forward it along, or
1635
                // interpret a return packet to a locally initialized one.
1636
                case cmd := <-s.htlcPlex:
3✔
1637
                        cmd.err <- s.handlePacketForward(cmd.pkt)
3✔
1638

1639
                // When this time ticks, then it indicates that we should
1640
                // collect all the forwarding events since the last internal,
1641
                // and write them out to our log.
1642
                case <-s.cfg.FwdEventTicker.Ticks():
3✔
1643
                        s.wg.Add(1)
3✔
1644
                        go func() {
6✔
1645
                                defer s.wg.Done()
3✔
1646

3✔
1647
                                if err := s.FlushForwardingEvents(); err != nil {
3✔
1648
                                        log.Errorf("Unable to flush "+
×
1649
                                                "forwarding events: %v", err)
×
1650
                                }
×
1651
                        }()
1652

1653
                // The log ticker has fired, so we'll calculate some forwarding
1654
                // stats for the last 10 seconds to display within the logs to
1655
                // users.
1656
                case <-s.cfg.LogEventTicker.Ticks():
3✔
1657
                        // First, we'll collate the current running tally of
3✔
1658
                        // our forwarding stats.
3✔
1659
                        prevSatSent := totalSatSent
3✔
1660
                        prevSatRecv := totalSatRecv
3✔
1661
                        prevNumUpdates := totalNumUpdates
3✔
1662

3✔
1663
                        var (
3✔
1664
                                newNumUpdates uint64
3✔
1665
                                newSatSent    btcutil.Amount
3✔
1666
                                newSatRecv    btcutil.Amount
3✔
1667
                        )
3✔
1668

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

3✔
1682
                        var (
3✔
1683
                                diffNumUpdates uint64
3✔
1684
                                diffSatSent    btcutil.Amount
3✔
1685
                                diffSatRecv    btcutil.Amount
3✔
1686
                        )
3✔
1687

3✔
1688
                        // If this is the first time we're computing these
3✔
1689
                        // stats, then the diff is just the new value. We do
3✔
1690
                        // this in order to avoid integer underflow issues.
3✔
1691
                        if prevNumUpdates == 0 {
6✔
1692
                                diffNumUpdates = newNumUpdates
3✔
1693
                                diffSatSent = newSatSent
3✔
1694
                                diffSatRecv = newSatRecv
3✔
1695
                        } else {
6✔
1696
                                diffNumUpdates = newNumUpdates - prevNumUpdates
3✔
1697
                                diffSatSent = newSatSent - prevSatSent
3✔
1698
                                diffSatRecv = newSatRecv - prevSatRecv
3✔
1699
                        }
3✔
1700

1701
                        // If the diff of num updates is zero, then we haven't
1702
                        // forwarded anything in the last 10 seconds, so we can
1703
                        // skip this update.
1704
                        if diffNumUpdates == 0 {
6✔
1705
                                continue
3✔
1706
                        }
1707

1708
                        // If the diff of num updates is negative, then some
1709
                        // links may have been unregistered from the switch, so
1710
                        // we'll update our stats to only include our registered
1711
                        // links.
1712
                        if int64(diffNumUpdates) < 0 {
6✔
1713
                                totalNumUpdates = newNumUpdates
3✔
1714
                                totalSatSent = newSatSent
3✔
1715
                                totalSatRecv = newSatRecv
3✔
1716
                                continue
3✔
1717
                        }
1718

1719
                        // Otherwise, we'll log this diff, then accumulate the
1720
                        // new stats into the running total.
1721
                        log.Debugf("Sent %d satoshis and received %d satoshis "+
3✔
1722
                                "in the last 10 seconds (%f tx/sec)",
3✔
1723
                                diffSatSent, diffSatRecv,
3✔
1724
                                float64(diffNumUpdates)/10)
3✔
1725

3✔
1726
                        totalNumUpdates += diffNumUpdates
3✔
1727
                        totalSatSent += diffSatSent
3✔
1728
                        totalSatRecv += diffSatRecv
3✔
1729

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

1740
                        // Batch ack the settle/fail entries.
1741
                        if err := s.ackSettleFail(s.pendingSettleFails...); err != nil {
3✔
1742
                                log.Errorf("Unable to ack batch of settle/fails: %v", err)
×
1743
                                continue
×
1744
                        }
1745

1746
                        log.Tracef("Acked %d settle fails: %v",
3✔
1747
                                len(s.pendingSettleFails),
3✔
1748
                                lnutils.SpewLogClosure(s.pendingSettleFails))
3✔
1749

3✔
1750
                        // Reset the pendingSettleFails buffer while keeping acquired
3✔
1751
                        // memory.
3✔
1752
                        s.pendingSettleFails = s.pendingSettleFails[:0]
3✔
1753

1754
                case <-s.quit:
3✔
1755
                        return
3✔
1756
                }
1757
        }
1758
}
1759

1760
// Start starts all helper goroutines required for the operation of the switch.
1761
func (s *Switch) Start() error {
3✔
1762
        if !atomic.CompareAndSwapInt32(&s.started, 0, 1) {
3✔
1763
                log.Warn("Htlc Switch already started")
×
1764
                return errors.New("htlc switch already started")
×
1765
        }
×
1766

1767
        log.Infof("HTLC Switch starting")
3✔
1768

3✔
1769
        blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
1770
        if err != nil {
3✔
1771
                return err
×
1772
        }
×
1773
        s.blockEpochStream = blockEpochStream
3✔
1774

3✔
1775
        s.wg.Add(1)
3✔
1776
        go s.htlcForwarder()
3✔
1777

3✔
1778
        if err := s.reforwardResponses(); err != nil {
3✔
1779
                s.Stop()
×
1780
                log.Errorf("unable to reforward responses: %v", err)
×
1781
                return err
×
1782
        }
×
1783

1784
        if err := s.reforwardResolutions(); err != nil {
3✔
1785
                // We are already stopping so we can ignore the error.
×
1786
                _ = s.Stop()
×
1787
                log.Errorf("unable to reforward resolutions: %v", err)
×
1788
                return err
×
1789
        }
×
1790

1791
        return nil
3✔
1792
}
1793

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

1805
        switchPackets := make([]*htlcPacket, 0, len(resMsgs))
3✔
1806
        for _, resMsg := range resMsgs {
6✔
1807
                // If the open circuit no longer exists, then we can remove the
3✔
1808
                // message from the store.
3✔
1809
                outKey := CircuitKey{
3✔
1810
                        ChanID: resMsg.SourceChan,
3✔
1811
                        HtlcID: resMsg.HtlcIndex,
3✔
1812
                }
3✔
1813

3✔
1814
                if s.circuits.LookupOpenCircuit(outKey) == nil {
6✔
1815
                        // The open circuit doesn't exist.
3✔
1816
                        err := s.resMsgStore.deleteResolutionMsg(&outKey)
3✔
1817
                        if err != nil {
3✔
1818
                                return err
×
1819
                        }
×
1820

1821
                        continue
3✔
1822
                }
1823

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

3✔
1834
                if resMsg.Failure != nil {
6✔
1835
                        resPkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1836
                } else {
3✔
1837
                        resPkt.htlc = &lnwire.UpdateFulfillHTLC{
×
1838
                                PaymentPreimage: *resMsg.PreImage,
×
1839
                        }
×
1840
                }
×
1841

1842
                switchPackets = append(switchPackets, resPkt)
3✔
1843
        }
1844

1845
        // We'll now dispatch the set of resolution messages to the proper
1846
        // destination. An error is only encountered here if the switch is
1847
        // shutting down.
1848
        if err := s.ForwardPackets(nil, switchPackets...); err != nil {
3✔
1849
                return err
×
1850
        }
×
1851

1852
        return nil
3✔
1853
}
1854

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

1866
        for _, openChannel := range openChannels {
6✔
1867
                shortChanID := openChannel.ShortChanID()
3✔
1868

3✔
1869
                // Locally-initiated payments never need reforwarding.
3✔
1870
                if shortChanID == hop.Source {
6✔
1871
                        continue
3✔
1872
                }
1873

1874
                // If the channel is pending, it should have no forwarding
1875
                // packages, and nothing to reforward.
1876
                if openChannel.IsPending {
3✔
1877
                        continue
×
1878
                }
1879

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

1893
                s.reforwardSettleFails(fwdPkgs)
3✔
1894
        }
1895

1896
        return nil
3✔
1897
}
1898

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

3✔
1903
        var fwdPkgs []*channeldb.FwdPkg
3✔
1904
        if err := kvdb.View(s.cfg.DB, func(tx kvdb.RTx) error {
6✔
1905
                var err error
3✔
1906
                fwdPkgs, err = s.cfg.SwitchPackager.LoadChannelFwdPkgs(
3✔
1907
                        tx, source,
3✔
1908
                )
3✔
1909
                return err
3✔
1910
        }, func() {
6✔
1911
                fwdPkgs = nil
3✔
1912
        }); err != nil {
3✔
1913
                return nil, err
×
1914
        }
×
1915

1916
        return fwdPkgs, nil
3✔
1917
}
1918

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

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

3✔
1951
                                // Add the packet to the batch to be forwarded, and
3✔
1952
                                // notify the overflow queue that a spare spot has been
3✔
1953
                                // freed up within the commitment state.
3✔
1954
                                switchPackets = append(switchPackets, settlePacket)
3✔
1955

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

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

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

1995
// Stop gracefully stops all active helper goroutines, then waits until they've
1996
// exited.
1997
func (s *Switch) Stop() error {
3✔
1998
        if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
3✔
1999
                log.Warn("Htlc Switch already stopped")
×
2000
                return errors.New("htlc switch already shutdown")
×
2001
        }
×
2002

2003
        log.Info("HTLC Switch shutting down...")
3✔
2004
        defer log.Debug("HTLC Switch shutdown complete")
3✔
2005

3✔
2006
        close(s.quit)
3✔
2007

3✔
2008
        s.wg.Wait()
3✔
2009

3✔
2010
        // Wait until all active goroutines have finished exiting before
3✔
2011
        // stopping the mailboxes, otherwise the mailbox map could still be
3✔
2012
        // accessed and modified.
3✔
2013
        s.mailOrchestrator.Stop()
3✔
2014

3✔
2015
        return nil
3✔
2016
}
2017

2018
// CreateAndAddLink will create a link and then add it to the internal maps
2019
// when given a ChannelLinkConfig and LightningChannel.
2020
func (s *Switch) CreateAndAddLink(linkCfg ChannelLinkConfig,
2021
        lnChan *lnwallet.LightningChannel) error {
3✔
2022

3✔
2023
        link := NewChannelLink(linkCfg, lnChan)
3✔
2024
        return s.AddLink(link)
3✔
2025
}
3✔
2026

2027
// AddLink is used to initiate the handling of the add link command. The
2028
// request will be propagated and handled in the main goroutine.
2029
func (s *Switch) AddLink(link ChannelLink) error {
3✔
2030
        s.indexMtx.Lock()
3✔
2031
        defer s.indexMtx.Unlock()
3✔
2032

3✔
2033
        chanID := link.ChanID()
3✔
2034

3✔
2035
        // First, ensure that this link is not already active in the switch.
3✔
2036
        _, err := s.getLink(chanID)
3✔
2037
        if err == nil {
3✔
2038
                return fmt.Errorf("unable to add ChannelLink(%v), already "+
×
2039
                        "active", chanID)
×
2040
        }
×
2041

2042
        // Get and attach the mailbox for this link, which buffers packets in
2043
        // case there packets that we tried to deliver while this link was
2044
        // offline.
2045
        shortChanID := link.ShortChanID()
3✔
2046
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(chanID, shortChanID)
3✔
2047
        link.AttachMailBox(mailbox)
3✔
2048

3✔
2049
        // Attach the Switch's failAliasUpdate function to the link.
3✔
2050
        link.attachFailAliasUpdate(s.failAliasUpdate)
3✔
2051

3✔
2052
        if err := link.Start(); err != nil {
3✔
2053
                log.Errorf("AddLink failed to start link with chanID=%v: %v",
×
2054
                        chanID, err)
×
2055
                s.removeLink(chanID)
×
2056
                return err
×
2057
        }
×
2058

2059
        if shortChanID == hop.Source {
6✔
2060
                log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
3✔
2061
                        chanID, shortChanID)
3✔
2062

3✔
2063
                s.pendingLinkIndex[chanID] = link
3✔
2064
        } else {
6✔
2065
                log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
3✔
2066
                        chanID, shortChanID)
3✔
2067

3✔
2068
                s.addLiveLink(link)
3✔
2069
                s.mailOrchestrator.BindLiveShortChanID(
3✔
2070
                        mailbox, chanID, shortChanID,
3✔
2071
                )
3✔
2072
        }
3✔
2073

2074
        return nil
3✔
2075
}
2076

2077
// addLiveLink adds a link to all associated forwarding index, this makes it a
2078
// candidate for forwarding HTLCs.
2079
func (s *Switch) addLiveLink(link ChannelLink) {
3✔
2080
        linkScid := link.ShortChanID()
3✔
2081

3✔
2082
        // We'll add the link to the linkIndex which lets us quickly
3✔
2083
        // look up a channel when we need to close or register it, and
3✔
2084
        // the forwarding index which'll be used when forwarding HTLC's
3✔
2085
        // in the multi-hop setting.
3✔
2086
        s.linkIndex[link.ChanID()] = link
3✔
2087
        s.forwardingIndex[linkScid] = link
3✔
2088

3✔
2089
        // Next we'll add the link to the interface index so we can
3✔
2090
        // quickly look up all the channels for a particular node.
3✔
2091
        peerPub := link.PeerPubKey()
3✔
2092
        if _, ok := s.interfaceIndex[peerPub]; !ok {
6✔
2093
                s.interfaceIndex[peerPub] = make(map[lnwire.ChannelID]ChannelLink)
3✔
2094
        }
3✔
2095
        s.interfaceIndex[peerPub][link.ChanID()] = link
3✔
2096

3✔
2097
        s.updateLinkAliases(link)
3✔
2098
}
2099

2100
// UpdateLinkAliases is the externally exposed wrapper for updating link
2101
// aliases. It acquires the indexMtx and calls the internal method.
2102
func (s *Switch) UpdateLinkAliases(link ChannelLink) {
3✔
2103
        s.indexMtx.Lock()
3✔
2104
        defer s.indexMtx.Unlock()
3✔
2105

3✔
2106
        s.updateLinkAliases(link)
3✔
2107
}
3✔
2108

2109
// updateLinkAliases updates the aliases for a given link. This will cause the
2110
// htlcswitch to consult the alias manager on the up to date values of its
2111
// alias maps.
2112
//
2113
// NOTE: this MUST be called with the indexMtx held.
2114
func (s *Switch) updateLinkAliases(link ChannelLink) {
3✔
2115
        linkScid := link.ShortChanID()
3✔
2116

3✔
2117
        aliases := link.getAliases()
3✔
2118
        if link.isZeroConf() {
6✔
2119
                if link.zeroConfConfirmed() {
6✔
2120
                        // Since the zero-conf channel has confirmed, we can
3✔
2121
                        // populate the aliasToReal mapping.
3✔
2122
                        confirmedScid := link.confirmedScid()
3✔
2123

3✔
2124
                        for _, alias := range aliases {
6✔
2125
                                s.aliasToReal[alias] = confirmedScid
3✔
2126
                        }
3✔
2127

2128
                        // Add the confirmed SCID as a key in the baseIndex.
2129
                        s.baseIndex[confirmedScid] = linkScid
3✔
2130
                }
2131

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

2150
                for alias, real := range s.baseIndex {
6✔
2151
                        if real == linkScid {
6✔
2152
                                delete(s.baseIndex, alias)
3✔
2153
                        }
3✔
2154
                }
2155

2156
                // The link's SCID is the confirmed SCID for non-zero-conf
2157
                // option-scid-alias feature bit channels.
2158
                for _, alias := range aliases {
6✔
2159
                        s.aliasToReal[alias] = linkScid
3✔
2160
                        s.baseIndex[alias] = linkScid
3✔
2161
                }
3✔
2162

2163
                // Since the link's SCID is confirmed, it was not included in
2164
                // the baseIndex above as a key. Add it now.
2165
                s.baseIndex[linkScid] = linkScid
3✔
2166
        }
2167
}
2168

2169
// GetLink is used to initiate the handling of the get link command. The
2170
// request will be propagated/handled to/in the main goroutine.
2171
func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelUpdateHandler,
2172
        error) {
3✔
2173

3✔
2174
        s.indexMtx.RLock()
3✔
2175
        defer s.indexMtx.RUnlock()
3✔
2176

3✔
2177
        return s.getLink(chanID)
3✔
2178
}
3✔
2179

2180
// getLink returns the link stored in either the pending index or the live
2181
// lindex.
2182
func (s *Switch) getLink(chanID lnwire.ChannelID) (ChannelLink, error) {
3✔
2183
        link, ok := s.linkIndex[chanID]
3✔
2184
        if !ok {
6✔
2185
                link, ok = s.pendingLinkIndex[chanID]
3✔
2186
                if !ok {
6✔
2187
                        return nil, ErrChannelLinkNotFound
3✔
2188
                }
3✔
2189
        }
2190

2191
        return link, nil
3✔
2192
}
2193

2194
// GetLinkByShortID attempts to return the link which possesses the target short
2195
// channel ID.
2196
func (s *Switch) GetLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink,
2197
        error) {
3✔
2198

3✔
2199
        s.indexMtx.RLock()
3✔
2200
        defer s.indexMtx.RUnlock()
3✔
2201

3✔
2202
        link, err := s.getLinkByShortID(chanID)
3✔
2203
        if err != nil {
6✔
2204
                // If we failed to find the link under the passed-in SCID, we
3✔
2205
                // consult the Switch's baseIndex map to see if the confirmed
3✔
2206
                // SCID was used for a zero-conf channel.
3✔
2207
                aliasID, ok := s.baseIndex[chanID]
3✔
2208
                if !ok {
6✔
2209
                        return nil, err
3✔
2210
                }
3✔
2211

2212
                // An alias was found, use it to lookup if a link exists.
2213
                return s.getLinkByShortID(aliasID)
3✔
2214
        }
2215

2216
        return link, nil
3✔
2217
}
2218

2219
// getLinkByShortID attempts to return the link which possesses the target
2220
// short channel ID.
2221
//
2222
// NOTE: This MUST be called with the indexMtx held.
2223
func (s *Switch) getLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink, error) {
3✔
2224
        link, ok := s.forwardingIndex[chanID]
3✔
2225
        if !ok {
6✔
2226
                return nil, ErrChannelLinkNotFound
3✔
2227
        }
3✔
2228

2229
        return link, nil
3✔
2230
}
2231

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

3✔
2253
        log.Debugf("Querying outgoing link using chanID=%v, aliasID=%v", chanID,
3✔
2254
                aliasID)
3✔
2255

3✔
2256
        // Set the originalOutgoingChanID so the proper channel_update can be
3✔
2257
        // sent back if the option-scid-alias feature bit was negotiated.
3✔
2258
        pkt.originalOutgoingChanID = chanID
3✔
2259

3✔
2260
        if aliasID {
6✔
2261
                // Since outgoingChanID is an alias, we'll fetch the link via
3✔
2262
                // baseIndex.
3✔
2263
                baseScid, ok := s.baseIndex[chanID]
3✔
2264
                if !ok {
3✔
2265
                        // No mapping exists, bail.
×
2266
                        return nil, ErrChannelLinkNotFound
×
2267
                }
×
2268

2269
                // A mapping exists, so use baseScid to find the link in the
2270
                // forwardingIndex.
2271
                link, ok := s.forwardingIndex[baseScid]
3✔
2272
                if !ok {
3✔
2273
                        // Link not found, bail.
×
2274
                        return nil, ErrChannelLinkNotFound
×
2275
                }
×
2276

2277
                // Change the packet's outgoingChanID field so that errors are
2278
                // properly attributed.
2279
                pkt.outgoingChanID = baseScid
3✔
2280

3✔
2281
                // Return the link without checking if it's private or not.
3✔
2282
                return link, nil
3✔
2283
        }
2284

2285
        // The outgoingChanID is a confirmed SCID. Attempt to fetch the base
2286
        // SCID from baseIndex.
2287
        baseScid, ok := s.baseIndex[chanID]
3✔
2288
        if !ok {
6✔
2289
                // outgoingChanID is not a key in base index meaning this
3✔
2290
                // channel did not have the option-scid-alias feature bit
3✔
2291
                // negotiated. We'll fetch the link and return it.
3✔
2292
                link, ok := s.forwardingIndex[chanID]
3✔
2293
                if !ok {
6✔
2294
                        // The link wasn't found, bail out.
3✔
2295
                        return nil, ErrChannelLinkNotFound
3✔
2296
                }
3✔
2297

2298
                return link, nil
3✔
2299
        }
2300

2301
        // Fetch the link whose internal SCID is baseScid.
2302
        link, ok := s.forwardingIndex[baseScid]
3✔
2303
        if !ok {
3✔
2304
                // Link wasn't found, bail out.
×
2305
                return nil, ErrChannelLinkNotFound
×
2306
        }
×
2307

2308
        // If the link is unadvertised, we fail since the real SCID was used to
2309
        // forward over it and this is a channel where the option-scid-alias
2310
        // feature bit was negotiated.
2311
        if link.IsUnadvertised() {
3✔
2312
                log.Debugf("Link is unadvertised, chanID=%v, baseScid=%v",
×
2313
                        chanID, baseScid)
×
2314

×
2315
                return nil, ErrChannelLinkNotFound
×
2316
        }
×
2317

2318
        // The link is public so the confirmed SCID can be used to forward over
2319
        // it. We'll also replace pkt's outgoingChanID field so errors can
2320
        // properly be attributed in the calling function.
2321
        pkt.outgoingChanID = baseScid
3✔
2322
        return link, nil
3✔
2323
}
2324

2325
// HasActiveLink returns true if the given channel ID has a link in the link
2326
// index AND the link is eligible to forward.
2327
func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
3✔
2328
        s.indexMtx.RLock()
3✔
2329
        defer s.indexMtx.RUnlock()
3✔
2330

3✔
2331
        if link, ok := s.linkIndex[chanID]; ok {
6✔
2332
                return link.EligibleToForward()
3✔
2333
        }
3✔
2334

2335
        return false
3✔
2336
}
2337

2338
// RemoveLink purges the switch of any link associated with chanID. If a pending
2339
// or active link is not found, this method does nothing. Otherwise, the method
2340
// returns after the link has been completely shutdown.
2341
func (s *Switch) RemoveLink(chanID lnwire.ChannelID) {
3✔
2342
        s.indexMtx.Lock()
3✔
2343
        link, err := s.getLink(chanID)
3✔
2344
        if err != nil {
6✔
2345
                // If err is non-nil, this means that link is also nil. The
3✔
2346
                // link variable cannot be nil without err being non-nil.
3✔
2347
                s.indexMtx.Unlock()
3✔
2348
                log.Tracef("Unable to remove link for ChannelID(%v): %v",
3✔
2349
                        chanID, err)
3✔
2350
                return
3✔
2351
        }
3✔
2352

2353
        // Check if the link is already stopping and grab the stop chan if it
2354
        // is.
2355
        stopChan, ok := s.linkStopIndex[chanID]
3✔
2356
        if !ok {
6✔
2357
                // If the link is non-nil, it is not currently stopping, so
3✔
2358
                // we'll add a stop chan to the linkStopIndex.
3✔
2359
                stopChan = make(chan struct{})
3✔
2360
                s.linkStopIndex[chanID] = stopChan
3✔
2361
        }
3✔
2362
        s.indexMtx.Unlock()
3✔
2363

3✔
2364
        if ok {
3✔
2365
                // If the stop chan exists, we will wait for it to be closed.
×
2366
                // Once it is closed, we will exit.
×
2367
                select {
×
2368
                case <-stopChan:
×
2369
                        return
×
2370
                case <-s.quit:
×
2371
                        return
×
2372
                }
2373
        }
2374

2375
        // Stop the link before removing it from the maps.
2376
        link.Stop()
3✔
2377

3✔
2378
        s.indexMtx.Lock()
3✔
2379
        _ = s.removeLink(chanID)
3✔
2380

3✔
2381
        // Close stopChan and remove this link from the linkStopIndex.
3✔
2382
        // Deleting from the index and removing from the link must be done
3✔
2383
        // in the same block while the mutex is held.
3✔
2384
        close(stopChan)
3✔
2385
        delete(s.linkStopIndex, chanID)
3✔
2386
        s.indexMtx.Unlock()
3✔
2387
}
2388

2389
// removeLink is used to remove and stop the channel link.
2390
//
2391
// NOTE: This MUST be called with the indexMtx held.
2392
func (s *Switch) removeLink(chanID lnwire.ChannelID) ChannelLink {
3✔
2393
        log.Infof("Removing channel link with ChannelID(%v)", chanID)
3✔
2394

3✔
2395
        link, err := s.getLink(chanID)
3✔
2396
        if err != nil {
3✔
2397
                return nil
×
2398
        }
×
2399

2400
        // Remove the channel from live link indexes.
2401
        delete(s.pendingLinkIndex, link.ChanID())
3✔
2402
        delete(s.linkIndex, link.ChanID())
3✔
2403
        delete(s.forwardingIndex, link.ShortChanID())
3✔
2404

3✔
2405
        // If the link has been added to the peer index, then we'll move to
3✔
2406
        // delete the entry within the index.
3✔
2407
        peerPub := link.PeerPubKey()
3✔
2408
        if peerIndex, ok := s.interfaceIndex[peerPub]; ok {
6✔
2409
                delete(peerIndex, link.ChanID())
3✔
2410

3✔
2411
                // If after deletion, there are no longer any links, then we'll
3✔
2412
                // remove the interface map all together.
3✔
2413
                if len(peerIndex) == 0 {
6✔
2414
                        delete(s.interfaceIndex, peerPub)
3✔
2415
                }
3✔
2416
        }
2417

2418
        return link
3✔
2419
}
2420

2421
// UpdateShortChanID locates the link with the passed-in chanID and updates the
2422
// underlying channel state. This is only used in zero-conf channels to allow
2423
// the confirmed SCID to be updated.
2424
func (s *Switch) UpdateShortChanID(chanID lnwire.ChannelID) error {
3✔
2425
        s.indexMtx.Lock()
3✔
2426
        defer s.indexMtx.Unlock()
3✔
2427

3✔
2428
        // Locate the target link in the link index. If no such link exists,
3✔
2429
        // then we will ignore the request.
3✔
2430
        link, ok := s.linkIndex[chanID]
3✔
2431
        if !ok {
3✔
2432
                return fmt.Errorf("link %v not found", chanID)
×
2433
        }
×
2434

2435
        // Try to update the link's underlying channel state, returning early
2436
        // if this update failed.
2437
        _, err := link.UpdateShortChanID()
3✔
2438
        if err != nil {
3✔
2439
                return err
×
2440
        }
×
2441

2442
        // Since the zero-conf channel is confirmed, we should populate the
2443
        // aliasToReal map and update the baseIndex.
2444
        aliases := link.getAliases()
3✔
2445

3✔
2446
        confirmedScid := link.confirmedScid()
3✔
2447

3✔
2448
        for _, alias := range aliases {
6✔
2449
                s.aliasToReal[alias] = confirmedScid
3✔
2450
        }
3✔
2451

2452
        s.baseIndex[confirmedScid] = link.ShortChanID()
3✔
2453

3✔
2454
        return nil
3✔
2455
}
2456

2457
// GetLinksByInterface fetches all the links connected to a particular node
2458
// identified by the serialized compressed form of its public key.
2459
func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
2460
        error) {
3✔
2461

3✔
2462
        s.indexMtx.RLock()
3✔
2463
        defer s.indexMtx.RUnlock()
3✔
2464

3✔
2465
        var handlers []ChannelUpdateHandler
3✔
2466

3✔
2467
        links, err := s.getLinks(hop)
3✔
2468
        if err != nil {
6✔
2469
                return nil, err
3✔
2470
        }
3✔
2471

2472
        // Range over the returned []ChannelLink to convert them into
2473
        // []ChannelUpdateHandler.
2474
        for _, link := range links {
6✔
2475
                handlers = append(handlers, link)
3✔
2476
        }
3✔
2477

2478
        return handlers, nil
3✔
2479
}
2480

2481
// getLinks is function which returns the channel links of the peer by hop
2482
// destination id.
2483
//
2484
// NOTE: This MUST be called with the indexMtx held.
2485
func (s *Switch) getLinks(destination [33]byte) ([]ChannelLink, error) {
3✔
2486
        links, ok := s.interfaceIndex[destination]
3✔
2487
        if !ok {
6✔
2488
                return nil, ErrNoLinksFound
3✔
2489
        }
3✔
2490

2491
        channelLinks := make([]ChannelLink, 0, len(links))
3✔
2492
        for _, link := range links {
6✔
2493
                channelLinks = append(channelLinks, link)
3✔
2494
        }
3✔
2495

2496
        return channelLinks, nil
3✔
2497
}
2498

2499
// CircuitModifier returns a reference to subset of the interfaces provided by
2500
// the circuit map, to allow links to open and close circuits.
2501
func (s *Switch) CircuitModifier() CircuitModifier {
3✔
2502
        return s.circuits
3✔
2503
}
3✔
2504

2505
// CircuitLookup returns a reference to subset of the interfaces provided by the
2506
// circuit map, to allow looking up circuits.
2507
func (s *Switch) CircuitLookup() CircuitLookup {
3✔
2508
        return s.circuits
3✔
2509
}
3✔
2510

2511
// commitCircuits persistently adds a circuit to the switch's circuit map.
2512
func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
2513
        *CircuitFwdActions, error) {
×
2514

×
2515
        return s.circuits.CommitCircuits(circuits...)
×
2516
}
×
2517

2518
// FlushForwardingEvents flushes out the set of pending forwarding events to
2519
// the persistent log. This will be used by the switch to periodically flush
2520
// out the set of forwarding events to disk. External callers can also use this
2521
// method to ensure all data is flushed to dis before querying the log.
2522
func (s *Switch) FlushForwardingEvents() error {
3✔
2523
        // First, we'll obtain a copy of the current set of pending forwarding
3✔
2524
        // events.
3✔
2525
        s.fwdEventMtx.Lock()
3✔
2526

3✔
2527
        // If we won't have any forwarding events, then we can exit early.
3✔
2528
        if len(s.pendingFwdingEvents) == 0 {
6✔
2529
                s.fwdEventMtx.Unlock()
3✔
2530
                return nil
3✔
2531
        }
3✔
2532

2533
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
3✔
2534
        copy(events[:], s.pendingFwdingEvents[:])
3✔
2535

3✔
2536
        // With the copy obtained, we can now clear out the header pointer of
3✔
2537
        // the current slice. This way, we can re-use the underlying storage
3✔
2538
        // allocated for the slice.
3✔
2539
        s.pendingFwdingEvents = s.pendingFwdingEvents[:0]
3✔
2540
        s.fwdEventMtx.Unlock()
3✔
2541

3✔
2542
        // Finally, we'll write out the copied events to the persistent
3✔
2543
        // forwarding log.
3✔
2544
        return s.cfg.FwdingLog.AddForwardingEvents(events)
3✔
2545
}
2546

2547
// BestHeight returns the best height known to the switch.
2548
func (s *Switch) BestHeight() uint32 {
3✔
2549
        return atomic.LoadUint32(&s.bestHeight)
3✔
2550
}
3✔
2551

2552
// dustExceedsFeeThreshold takes in a ChannelLink, HTLC amount, and a boolean
2553
// to determine whether the default fee threshold has been exceeded. This
2554
// heuristic takes into account the trimmed-to-dust mechanism. The sum of the
2555
// commitment's dust with the mailbox's dust with the amount is checked against
2556
// the fee exposure threshold. If incoming is true, then the amount is not
2557
// included in the sum as it was already included in the commitment's dust. A
2558
// boolean is returned telling the caller whether the HTLC should be failed
2559
// back.
2560
func (s *Switch) dustExceedsFeeThreshold(link ChannelLink,
2561
        amount lnwire.MilliSatoshi, incoming bool) bool {
3✔
2562

3✔
2563
        // Retrieve the link's current commitment feerate and dustClosure.
3✔
2564
        feeRate := link.getFeeRate()
3✔
2565
        isDust := link.getDustClosure()
3✔
2566

3✔
2567
        // Evaluate if the HTLC is dust on either sides' commitment.
3✔
2568
        isLocalDust := isDust(
3✔
2569
                feeRate, incoming, lntypes.Local, amount.ToSatoshis(),
3✔
2570
        )
3✔
2571
        isRemoteDust := isDust(
3✔
2572
                feeRate, incoming, lntypes.Remote, amount.ToSatoshis(),
3✔
2573
        )
3✔
2574

3✔
2575
        if !(isLocalDust || isRemoteDust) {
6✔
2576
                // If the HTLC is not dust on either commitment, it's fine to
3✔
2577
                // forward.
3✔
2578
                return false
3✔
2579
        }
3✔
2580

2581
        // Fetch the dust sums currently in the mailbox for this link.
2582
        cid := link.ChanID()
3✔
2583
        sid := link.ShortChanID()
3✔
2584
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
3✔
2585
        localMailDust, remoteMailDust := mailbox.DustPackets()
3✔
2586

3✔
2587
        // If the htlc is dust on the local commitment, we'll obtain the dust
3✔
2588
        // sum for it.
3✔
2589
        if isLocalDust {
6✔
2590
                localSum := link.getDustSum(
3✔
2591
                        lntypes.Local, fn.None[chainfee.SatPerKWeight](),
3✔
2592
                )
3✔
2593
                localSum += localMailDust
3✔
2594

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

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

2607
        // Also check if the htlc is dust on the remote commitment, if we've
2608
        // reached this point.
2609
        if isRemoteDust {
6✔
2610
                remoteSum := link.getDustSum(
3✔
2611
                        lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
3✔
2612
                )
3✔
2613
                remoteSum += remoteMailDust
3✔
2614

3✔
2615
                // Optionally include the HTLC amount only for outgoing
3✔
2616
                // HTLCs.
3✔
2617
                if !incoming {
6✔
2618
                        remoteSum += amount
3✔
2619
                }
3✔
2620

2621
                // Finally check against the defined fee threshold.
2622
                if remoteSum > s.cfg.MaxFeeExposure {
3✔
2623
                        return true
×
2624
                }
×
2625
        }
2626

2627
        // If we reached this point, this HTLC is fine to forward.
2628
        return false
3✔
2629
}
2630

2631
// failMailboxUpdate is passed to the mailbox orchestrator which in turn passes
2632
// it to individual mailboxes. It allows the mailboxes to construct a
2633
// FailureMessage when failing back HTLC's due to expiry and may include an
2634
// alias in the ShortChannelID field. The outgoingScid is the SCID originally
2635
// used in the onion. The mailboxScid is the SCID that the mailbox and link
2636
// use. The mailboxScid is only used in the non-alias case, so it is always
2637
// the confirmed SCID.
2638
func (s *Switch) failMailboxUpdate(outgoingScid,
2639
        mailboxScid lnwire.ShortChannelID) lnwire.FailureMessage {
3✔
2640

3✔
2641
        // Try to use the failAliasUpdate function in case this is a channel
3✔
2642
        // that uses aliases. If it returns nil, we'll fallback to the original
3✔
2643
        // pre-alias behavior.
3✔
2644
        update := s.failAliasUpdate(outgoingScid, false)
3✔
2645
        if update == nil {
6✔
2646
                // Execute the fallback behavior.
3✔
2647
                var err error
3✔
2648
                update, err = s.cfg.FetchLastChannelUpdate(mailboxScid)
3✔
2649
                if err != nil {
3✔
2650
                        return &lnwire.FailTemporaryNodeFailure{}
×
2651
                }
×
2652
        }
2653

2654
        return lnwire.NewTemporaryChannelFailure(update)
3✔
2655
}
2656

2657
// failAliasUpdate prepares a ChannelUpdate for a failed incoming or outgoing
2658
// HTLC on a channel where the option-scid-alias feature bit was negotiated. If
2659
// the associated channel is not one of these, this function will return nil
2660
// and the caller is expected to handle this properly. In this case, a return
2661
// to the original non-alias behavior is expected.
2662
func (s *Switch) failAliasUpdate(scid lnwire.ShortChannelID,
2663
        incoming bool) *lnwire.ChannelUpdate1 {
3✔
2664

3✔
2665
        // This function does not defer the unlocking because of the database
3✔
2666
        // lookups for ChannelUpdate.
3✔
2667
        s.indexMtx.RLock()
3✔
2668

3✔
2669
        if s.cfg.IsAlias(scid) {
6✔
2670
                // The alias SCID was used. In the incoming case this means
3✔
2671
                // the channel is zero-conf as the link sets the scid. In the
3✔
2672
                // outgoing case, the sender set the scid to use and may be
3✔
2673
                // either the alias or the confirmed one, if it exists.
3✔
2674
                realScid, ok := s.aliasToReal[scid]
3✔
2675
                if !ok {
3✔
2676
                        // The real, confirmed SCID does not exist yet. Find
×
2677
                        // the "base" SCID that the link uses via the
×
2678
                        // baseIndex. If we can't find it, return nil. This
×
2679
                        // means the channel is zero-conf.
×
2680
                        baseScid, ok := s.baseIndex[scid]
×
2681
                        s.indexMtx.RUnlock()
×
2682
                        if !ok {
×
2683
                                return nil
×
2684
                        }
×
2685

2686
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2687
                        if err != nil {
×
2688
                                return nil
×
2689
                        }
×
2690

2691
                        // Replace the baseScid with the passed-in alias.
2692
                        update.ShortChannelID = scid
×
2693
                        sig, err := s.cfg.SignAliasUpdate(update)
×
2694
                        if err != nil {
×
2695
                                return nil
×
2696
                        }
×
2697

2698
                        update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2699
                        if err != nil {
×
2700
                                return nil
×
2701
                        }
×
2702

2703
                        return update
×
2704
                }
2705

2706
                s.indexMtx.RUnlock()
3✔
2707

3✔
2708
                // Fetch the SCID via the confirmed SCID and replace it with
3✔
2709
                // the alias.
3✔
2710
                update, err := s.cfg.FetchLastChannelUpdate(realScid)
3✔
2711
                if err != nil {
6✔
2712
                        return nil
3✔
2713
                }
3✔
2714

2715
                // In the incoming case, we want to ensure that we don't leak
2716
                // the UTXO in case the channel is private. In the outgoing
2717
                // case, since the alias was used, we do the same thing.
2718
                update.ShortChannelID = scid
3✔
2719
                sig, err := s.cfg.SignAliasUpdate(update)
3✔
2720
                if err != nil {
3✔
2721
                        return nil
×
2722
                }
×
2723

2724
                update.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
2725
                if err != nil {
3✔
2726
                        return nil
×
2727
                }
×
2728

2729
                return update
3✔
2730
        }
2731

2732
        // If the confirmed SCID is not in baseIndex, this is not an
2733
        // option-scid-alias or zero-conf channel.
2734
        baseScid, ok := s.baseIndex[scid]
3✔
2735
        if !ok {
6✔
2736
                s.indexMtx.RUnlock()
3✔
2737
                return nil
3✔
2738
        }
3✔
2739

2740
        // Fetch the link so we can get an alias to use in the ShortChannelID
2741
        // of the ChannelUpdate.
2742
        link, ok := s.forwardingIndex[baseScid]
×
2743
        s.indexMtx.RUnlock()
×
2744
        if !ok {
×
2745
                // This should never happen, but if it does for some reason,
×
2746
                // fallback to the old behavior.
×
2747
                return nil
×
2748
        }
×
2749

2750
        aliases := link.getAliases()
×
2751
        if len(aliases) == 0 {
×
2752
                // This should never happen, but if it does, fallback.
×
2753
                return nil
×
2754
        }
×
2755

2756
        // Fetch the ChannelUpdate via the real, confirmed SCID.
2757
        update, err := s.cfg.FetchLastChannelUpdate(scid)
×
2758
        if err != nil {
×
2759
                return nil
×
2760
        }
×
2761

2762
        // The incoming case will replace the ShortChannelID in the retrieved
2763
        // ChannelUpdate with the alias to ensure no privacy leak occurs. This
2764
        // would happen if a private non-zero-conf option-scid-alias
2765
        // feature-bit channel leaked its UTXO here rather than supplying an
2766
        // alias. In the outgoing case, the confirmed SCID was actually used
2767
        // for forwarding in the onion, so no replacement is necessary as the
2768
        // sender knows the scid.
2769
        if incoming {
×
2770
                // We will replace and sign the update with the first alias.
×
2771
                // Since this happens on the incoming side, it's not actually
×
2772
                // possible to know what the sender used in the onion.
×
2773
                update.ShortChannelID = aliases[0]
×
2774
                sig, err := s.cfg.SignAliasUpdate(update)
×
2775
                if err != nil {
×
2776
                        return nil
×
2777
                }
×
2778

2779
                update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2780
                if err != nil {
×
2781
                        return nil
×
2782
                }
×
2783
        }
2784

2785
        return update
×
2786
}
2787

2788
// AddAliasForLink instructs the Switch to update its in-memory maps to reflect
2789
// that a link has a new alias.
2790
func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
2791
        alias lnwire.ShortChannelID) error {
×
2792

×
2793
        // Fetch the link so that we can update the underlying channel's set of
×
2794
        // aliases.
×
2795
        s.indexMtx.RLock()
×
2796
        link, err := s.getLink(chanID)
×
2797
        s.indexMtx.RUnlock()
×
2798
        if err != nil {
×
2799
                return err
×
2800
        }
×
2801

2802
        // If the link is a channel where the option-scid-alias feature bit was
2803
        // not negotiated, we'll return an error.
2804
        if !link.negotiatedAliasFeature() {
×
2805
                return fmt.Errorf("attempted to update non-alias channel")
×
2806
        }
×
2807

2808
        linkScid := link.ShortChanID()
×
2809

×
2810
        // We'll update the maps so the Switch includes this alias in its
×
2811
        // forwarding decisions.
×
2812
        if link.isZeroConf() {
×
2813
                if link.zeroConfConfirmed() {
×
2814
                        // If the channel has confirmed on-chain, we'll
×
2815
                        // add this alias to the aliasToReal map.
×
2816
                        confirmedScid := link.confirmedScid()
×
2817

×
2818
                        s.aliasToReal[alias] = confirmedScid
×
2819
                }
×
2820

2821
                // Add this alias to the baseIndex mapping.
2822
                s.baseIndex[alias] = linkScid
×
2823
        } else if link.negotiatedAliasFeature() {
×
2824
                // The channel is confirmed, so we'll populate the aliasToReal
×
2825
                // and baseIndex maps.
×
2826
                s.aliasToReal[alias] = linkScid
×
2827
                s.baseIndex[alias] = linkScid
×
2828
        }
×
2829

2830
        return nil
×
2831
}
2832

2833
// handlePacketAdd handles forwarding an Add packet.
2834
func (s *Switch) handlePacketAdd(packet *htlcPacket,
2835
        htlc *lnwire.UpdateAddHTLC) error {
3✔
2836

3✔
2837
        // Check if the node is set to reject all onward HTLCs and also make
3✔
2838
        // sure that HTLC is not from the source node.
3✔
2839
        if s.cfg.RejectHTLC {
6✔
2840
                failure := NewDetailedLinkError(
3✔
2841
                        &lnwire.FailChannelDisabled{},
3✔
2842
                        OutgoingFailureForwardsDisabled,
3✔
2843
                )
3✔
2844

3✔
2845
                return s.failAddPacket(packet, failure)
3✔
2846
        }
3✔
2847

2848
        // Before we attempt to find a non-strict forwarding path for this
2849
        // htlc, check whether the htlc is being routed over the same incoming
2850
        // and outgoing channel. If our node does not allow forwards of this
2851
        // nature, we fail the htlc early. This check is in place to disallow
2852
        // inefficiently routed htlcs from locking up our balance. With
2853
        // channels where the option-scid-alias feature was negotiated, we also
2854
        // have to be sure that the IDs aren't the same since one or both could
2855
        // be an alias.
2856
        linkErr := s.checkCircularForward(
3✔
2857
                packet.incomingChanID, packet.outgoingChanID,
3✔
2858
                s.cfg.AllowCircularRoute, htlc.PaymentHash,
3✔
2859
        )
3✔
2860
        if linkErr != nil {
3✔
2861
                return s.failAddPacket(packet, linkErr)
×
2862
        }
×
2863

2864
        s.indexMtx.RLock()
3✔
2865
        targetLink, err := s.getLinkByMapping(packet)
3✔
2866
        if err != nil {
6✔
2867
                s.indexMtx.RUnlock()
3✔
2868

3✔
2869
                log.Debugf("unable to find link with "+
3✔
2870
                        "destination %v", packet.outgoingChanID)
3✔
2871

3✔
2872
                // If packet was forwarded from another channel link than we
3✔
2873
                // should notify this link that some error occurred.
3✔
2874
                linkError := NewLinkError(
3✔
2875
                        &lnwire.FailUnknownNextPeer{},
3✔
2876
                )
3✔
2877

3✔
2878
                return s.failAddPacket(packet, linkError)
3✔
2879
        }
3✔
2880
        targetPeerKey := targetLink.PeerPubKey()
3✔
2881
        interfaceLinks, _ := s.getLinks(targetPeerKey)
3✔
2882
        s.indexMtx.RUnlock()
3✔
2883

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

3✔
2890
        // Find all destination channel links with appropriate bandwidth.
3✔
2891
        var destinations []ChannelLink
3✔
2892
        for _, link := range interfaceLinks {
6✔
2893
                var failure *LinkError
3✔
2894

3✔
2895
                // We'll skip any links that aren't yet eligible for
3✔
2896
                // forwarding.
3✔
2897
                if !link.EligibleToForward() {
3✔
2898
                        failure = NewDetailedLinkError(
×
2899
                                &lnwire.FailUnknownNextPeer{},
×
2900
                                OutgoingFailureLinkNotEligible,
×
2901
                        )
×
2902
                } else {
3✔
2903
                        // We'll ensure that the HTLC satisfies the current
3✔
2904
                        // forwarding conditions of this target link.
3✔
2905
                        currentHeight := atomic.LoadUint32(&s.bestHeight)
3✔
2906
                        failure = link.CheckHtlcForward(
3✔
2907
                                htlc.PaymentHash, packet.incomingAmount,
3✔
2908
                                packet.amount, packet.incomingTimeout,
3✔
2909
                                packet.outgoingTimeout, packet.inboundFee,
3✔
2910
                                currentHeight, packet.originalOutgoingChanID,
3✔
2911
                                htlc.CustomRecords,
3✔
2912
                        )
3✔
2913
                }
3✔
2914

2915
                // If this link can forward the htlc, add it to the set of
2916
                // destinations.
2917
                if failure == nil {
6✔
2918
                        destinations = append(destinations, link)
3✔
2919
                        continue
3✔
2920
                }
2921

2922
                linkErrs[link.ShortChanID()] = failure
3✔
2923
        }
2924

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

2946
                log.Tracef("incoming HTLC(%x) violated "+
3✔
2947
                        "target outgoing link (id=%v) policy: %v",
3✔
2948
                        htlc.PaymentHash[:], packet.outgoingChanID,
3✔
2949
                        linkErr)
3✔
2950

3✔
2951
                return s.failAddPacket(packet, linkErr)
3✔
2952
        }
2953

2954
        // Choose a random link out of the set of links that can forward this
2955
        // htlc. The reason for randomization is to evenly distribute the htlc
2956
        // load without making assumptions about what the best channel is.
2957
        //nolint:gosec
2958
        destination := destinations[rand.Intn(len(destinations))]
3✔
2959

3✔
2960
        // Retrieve the incoming link by its ShortChannelID. Note that the
3✔
2961
        // incomingChanID is never set to hop.Source here.
3✔
2962
        s.indexMtx.RLock()
3✔
2963
        incomingLink, err := s.getLinkByShortID(packet.incomingChanID)
3✔
2964
        s.indexMtx.RUnlock()
3✔
2965
        if err != nil {
3✔
2966
                // If we couldn't find the incoming link, we can't evaluate the
×
2967
                // incoming's exposure to dust, so we just fail the HTLC back.
×
2968
                linkErr := NewLinkError(
×
2969
                        &lnwire.FailTemporaryChannelFailure{},
×
2970
                )
×
2971

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

2975
        // Evaluate whether this HTLC would increase our fee exposure over the
2976
        // threshold on the incoming link. If it does, fail it backwards.
2977
        if s.dustExceedsFeeThreshold(
3✔
2978
                incomingLink, packet.incomingAmount, true,
3✔
2979
        ) {
3✔
2980
                // The incoming dust exceeds the threshold, so we fail the add
×
2981
                // back.
×
2982
                linkErr := NewLinkError(
×
2983
                        &lnwire.FailTemporaryChannelFailure{},
×
2984
                )
×
2985

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

2989
        // Also evaluate whether this HTLC would increase our fee exposure over
2990
        // the threshold on the destination link. If it does, fail it back.
2991
        if s.dustExceedsFeeThreshold(
3✔
2992
                destination, packet.amount, false,
3✔
2993
        ) {
3✔
2994
                // The outgoing dust exceeds the threshold, so we fail the add
×
2995
                // back.
×
2996
                linkErr := NewLinkError(
×
2997
                        &lnwire.FailTemporaryChannelFailure{},
×
2998
                )
×
2999

×
3000
                return s.failAddPacket(packet, linkErr)
×
3001
        }
×
3002

3003
        // Send the packet to the destination channel link which manages the
3004
        // channel.
3005
        packet.outgoingChanID = destination.ShortChanID()
3✔
3006

3✔
3007
        return destination.handleSwitchPacket(packet)
3✔
3008
}
3009

3010
// handlePacketSettle handles forwarding a settle packet.
3011
func (s *Switch) handlePacketSettle(packet *htlcPacket) error {
3✔
3012
        // If the source of this packet has not been set, use the circuit map
3✔
3013
        // to lookup the origin.
3✔
3014
        circuit, err := s.closeCircuit(packet)
3✔
3015

3✔
3016
        // If the circuit is in the process of closing, we will return a nil as
3✔
3017
        // there's another packet handling undergoing.
3✔
3018
        if errors.Is(err, ErrCircuitClosing) {
6✔
3019
                log.Debugf("Circuit is closing for packet=%v", packet)
3✔
3020
                return nil
3✔
3021
        }
3✔
3022

3023
        // Exit early if there's another error.
3024
        if err != nil {
3✔
3025
                return err
×
3026
        }
×
3027

3028
        // closeCircuit returns a nil circuit when a settle packet returns an
3029
        // ErrUnknownCircuit error upon the inner call to CloseCircuit.
3030
        //
3031
        // NOTE: We can only get a nil circuit when it has already been deleted
3032
        // and when `UpdateFulfillHTLC` is received. After which `RevokeAndAck`
3033
        // is received, which invokes `processRemoteSettleFails` in its link.
3034
        if circuit == nil {
6✔
3035
                log.Debugf("Circuit already closed for packet=%v", packet)
3✔
3036
                return nil
3✔
3037
        }
3✔
3038

3039
        localHTLC := packet.incomingChanID == hop.Source
3✔
3040

3✔
3041
        // If this is a locally initiated HTLC, we need to handle the packet by
3✔
3042
        // storing the network result.
3✔
3043
        //
3✔
3044
        // A blank IncomingChanID in a circuit indicates that it is a pending
3✔
3045
        // user-initiated payment.
3✔
3046
        //
3✔
3047
        // NOTE: `closeCircuit` modifies the state of `packet`.
3✔
3048
        if localHTLC {
6✔
3049
                // TODO(yy): remove the goroutine and send back the error here.
3✔
3050
                s.wg.Add(1)
3✔
3051
                go s.handleLocalResponse(packet)
3✔
3052

3✔
3053
                // If this is a locally initiated HTLC, there's no need to
3✔
3054
                // forward it so we exit.
3✔
3055
                return nil
3✔
3056
        }
3✔
3057

3058
        // If this is an HTLC settle, and it wasn't from a locally initiated
3059
        // HTLC, then we'll log a forwarding event so we can flush it to disk
3060
        // later.
3061
        if circuit.Outgoing != nil {
6✔
3062
                log.Infof("Forwarded HTLC(%x) of %v (fee: %v) "+
3✔
3063
                        "from IncomingChanID(%v) to OutgoingChanID(%v)",
3✔
3064
                        circuit.PaymentHash[:], circuit.OutgoingAmount,
3✔
3065
                        circuit.IncomingAmount-circuit.OutgoingAmount,
3✔
3066
                        circuit.Incoming.ChanID, circuit.Outgoing.ChanID)
3✔
3067

3✔
3068
                s.fwdEventMtx.Lock()
3✔
3069
                s.pendingFwdingEvents = append(
3✔
3070
                        s.pendingFwdingEvents,
3✔
3071
                        channeldb.ForwardingEvent{
3✔
3072
                                Timestamp:      time.Now(),
3✔
3073
                                IncomingChanID: circuit.Incoming.ChanID,
3✔
3074
                                OutgoingChanID: circuit.Outgoing.ChanID,
3✔
3075
                                AmtIn:          circuit.IncomingAmount,
3✔
3076
                                AmtOut:         circuit.OutgoingAmount,
3✔
3077
                        },
3✔
3078
                )
3✔
3079
                s.fwdEventMtx.Unlock()
3✔
3080
        }
3✔
3081

3082
        // Deliver this packet.
3083
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3084
}
3085

3086
// handlePacketFail handles forwarding a fail packet.
3087
func (s *Switch) handlePacketFail(packet *htlcPacket,
3088
        htlc *lnwire.UpdateFailHTLC) error {
3✔
3089

3✔
3090
        // If the source of this packet has not been set, use the circuit map
3✔
3091
        // to lookup the origin.
3✔
3092
        circuit, err := s.closeCircuit(packet)
3✔
3093
        if err != nil {
3✔
3094
                return err
×
3095
        }
×
3096

3097
        // If this is a locally initiated HTLC, we need to handle the packet by
3098
        // storing the network result.
3099
        //
3100
        // A blank IncomingChanID in a circuit indicates that it is a pending
3101
        // user-initiated payment.
3102
        //
3103
        // NOTE: `closeCircuit` modifies the state of `packet`.
3104
        if packet.incomingChanID == hop.Source {
6✔
3105
                // TODO(yy): remove the goroutine and send back the error here.
3✔
3106
                s.wg.Add(1)
3✔
3107
                go s.handleLocalResponse(packet)
3✔
3108

3✔
3109
                // If this is a locally initiated HTLC, there's no need to
3✔
3110
                // forward it so we exit.
3✔
3111
                return nil
3✔
3112
        }
3✔
3113

3114
        // Exit early if this hasSource is true. This flag is only set via
3115
        // mailbox's `FailAdd`. This method has two callsites,
3116
        // - the packet has timed out after `MailboxDeliveryTimeout`, defaults
3117
        //   to 1 min.
3118
        // - the HTLC fails the validation in `channel.AddHTLC`.
3119
        // In either case, the `Reason` field is populated. Thus there's no
3120
        // need to proceed and extract the failure reason below.
3121
        if packet.hasSource {
3✔
3122
                // Deliver this packet.
×
3123
                return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
×
3124
        }
×
3125

3126
        // HTLC resolutions and messages restored from disk don't have the
3127
        // obfuscator set from the original htlc add packet - set it here for
3128
        // use in blinded errors.
3129
        packet.obfuscator = circuit.ErrorEncrypter
3✔
3130

3✔
3131
        switch {
3✔
3132
        // No message to encrypt, locally sourced payment.
3133
        case circuit.ErrorEncrypter == nil:
×
3134
                // TODO(yy) further check this case as we shouldn't end up here
3135
                // as `isLocal` is already false.
3136

3137
        // If this is a resolution message, then we'll need to encrypt it as
3138
        // it's actually internally sourced.
3139
        case packet.isResolution:
3✔
3140
                var err error
3✔
3141
                // TODO(roasbeef): don't need to pass actually?
3✔
3142
                failure := &lnwire.FailPermanentChannelFailure{}
3✔
3143
                htlc.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
3✔
3144
                        failure,
3✔
3145
                )
3✔
3146
                if err != nil {
3✔
3147
                        err = fmt.Errorf("unable to obfuscate error: %w", err)
×
3148
                        log.Error(err)
×
3149
                }
×
3150

3151
        // Alternatively, if the remote party sends us an
3152
        // UpdateFailMalformedHTLC, then we'll need to convert this into a
3153
        // proper well formatted onion error as there's no HMAC currently.
3154
        case packet.convertedError:
3✔
3155
                log.Infof("Converting malformed HTLC error for circuit for "+
3✔
3156
                        "Circuit(%x: (%s, %d) <-> (%s, %d))",
3✔
3157
                        packet.circuit.PaymentHash,
3✔
3158
                        packet.incomingChanID, packet.incomingHTLCID,
3✔
3159
                        packet.outgoingChanID, packet.outgoingHTLCID)
3✔
3160

3✔
3161
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
3✔
3162
                        htlc.Reason,
3✔
3163
                )
3✔
3164

3165
        default:
3✔
3166
                // Otherwise, it's a forwarded error, so we'll perform a
3✔
3167
                // wrapper encryption as normal.
3✔
3168
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
3✔
3169
                        htlc.Reason,
3✔
3170
                )
3✔
3171
        }
3172

3173
        // Deliver this packet.
3174
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3175
}
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