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

lightningnetwork / lnd / 17190810624

24 Aug 2025 03:58PM UTC coverage: 66.74% (+9.4%) from 57.321%
17190810624

Pull #10167

github

web-flow
Merge 33cec4f6a into 0c2f045f5
Pull Request #10167: multi: bump Go to 1.24.6

6 of 40 new or added lines in 10 files covered. (15.0%)

12 existing lines in 6 files now uncovered.

135947 of 203696 relevant lines covered (66.74%)

21470.9 hits per line

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

82.6
/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) {
344✔
362
        resStore := newResolutionStore(cfg.DB)
344✔
363

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

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

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

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

344✔
402
        return s, nil
344✔
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 {
4✔
420
        errChan := make(chan error, 1)
4✔
421

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

431
        select {
4✔
432
        case err := <-errChan:
4✔
433
                return err
4✔
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) {
310✔
465

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

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

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

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

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

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

304✔
518
                // Extract the result and pass it to the result channel.
304✔
519
                result, err := s.extractResult(
304✔
520
                        deobfuscator, n, attemptID, paymentHash,
304✔
521
                )
304✔
522
                if err != nil {
304✔
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
304✔
531
        }()
532

533
        return resultChan, nil
308✔
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 {
419✔
550

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

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

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

1✔
604
                return errFeeExposureExceeded
1✔
605
        }
1✔
606

607
        circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
414✔
608
        actions, err := s.circuits.CommitCircuits(circuit)
414✔
609
        if err != nil {
414✔
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 {
414✔
616
        case len(actions.Drops) == 1:
1✔
617
                return ErrDuplicateAdd
1✔
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
413✔
626

413✔
627
        return link.handleSwitchPacket(packet)
413✔
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 {
5✔
665

5✔
666
        circuit := s.circuits.LookupOpenCircuit(models.CircuitKey{
5✔
667
                ChanID: chanID,
5✔
668
                HtlcID: htlcIndex,
5✔
669
        })
5✔
670
        return circuit != nil && circuit.Incoming.ChanID != hop.Source
5✔
671
}
5✔
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 {
873✔
681

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

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

873✔
693
        // No packets, nothing to do.
873✔
694
        if len(packets) == 0 {
1,096✔
695
                return nil
223✔
696
        }
223✔
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
653✔
701
        wg.Add(1)
653✔
702
        defer wg.Done()
653✔
703

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

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

747
        // Write any circuits that we found to disk.
748
        actions, err := s.circuits.CommitCircuits(circuits...)
90✔
749
        if err != nil {
90✔
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
90✔
760
        for _, packet := range addBatch {
180✔
761
                switch {
90✔
762
                case len(actions.Adds) > 0 && packet.circuit == actions.Adds[0]:
86✔
763
                        addedPackets = append(addedPackets, packet)
86✔
764
                        actions.Adds = actions.Adds[1:]
86✔
765

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

769
                case len(actions.Fails) > 0 && packet.circuit == actions.Fails[0]:
3✔
770
                        failedPackets = append(failedPackets, packet)
3✔
771
                        actions.Fails = actions.Fails[1:]
3✔
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 {
176✔
778
                err := s.routeAsync(packet, fwdChan, linkQuit)
86✔
779
                if err != nil {
87✔
780
                        return fmt.Errorf("failed to forward packet %w", err)
1✔
781
                }
1✔
782
                numSent++
85✔
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 {
92✔
789
                var failure lnwire.FailureMessage
3✔
790
                incomingID := failedPackets[0].incomingChanID
3✔
791

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

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

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

823
        return nil
89✔
824
}
825

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

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

652✔
835
        numSent := *num
652✔
836
        for i := 0; i < numSent; i++ {
1,274✔
837
                select {
622✔
838
                case err := <-fwdChan:
620✔
839
                        if err != nil {
646✔
840
                                log.Errorf("Unhandled error while reforwarding htlc "+
26✔
841
                                        "settle/fail over htlcswitch: %v", err)
26✔
842
                        }
26✔
843
                case <-s.quit:
2✔
844
                        log.Errorf("unable to forward htlc packet " +
2✔
845
                                "htlc switch was stopped")
2✔
846
                        return
2✔
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 {
648✔
858

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

648✔
864
        select {
648✔
865
        case s.htlcPlex <- command:
622✔
866
                return nil
622✔
867
        case <-linkQuit:
11✔
868
                return ErrLinkShuttingDown
11✔
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) {
419✔
879

419✔
880
        // Try to find links by node destination.
419✔
881
        s.indexMtx.RLock()
419✔
882
        link, err := s.getLinkByShortID(pkt.outgoingChanID)
419✔
883
        if err != nil {
423✔
884
                // If the link was not found for the outgoingChanID, an outside
4✔
885
                // subsystem may be using the confirmed SCID of a zero-conf
4✔
886
                // channel. In this case, we'll consult the Switch maps to see
4✔
887
                // if an alias exists and use the alias to lookup the link.
4✔
888
                // This extra step is a consequence of not updating the Switch
4✔
889
                // forwardingIndex when a zero-conf channel is confirmed. We
4✔
890
                // don't need to change the outgoingChanID since the link will
4✔
891
                // do that upon receiving the packet.
4✔
892
                baseScid, ok := s.baseIndex[pkt.outgoingChanID]
4✔
893
                if !ok {
7✔
894
                        s.indexMtx.RUnlock()
3✔
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)
4✔
902
                if err != nil {
4✔
903
                        s.indexMtx.RUnlock()
×
904
                        log.Errorf("Link %v not found", baseScid)
×
905
                        return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
×
906
                }
×
907
        }
908
        // We finished looking up the indexes, so we can unlock the mutex before
909
        // performing the link operations which might also acquire the lock
910
        // in case e.g. failAliasUpdate is called.
911
        s.indexMtx.RUnlock()
419✔
912

419✔
913
        if !link.EligibleToForward() {
420✔
914
                log.Errorf("Link %v is not available to forward",
1✔
915
                        pkt.outgoingChanID)
1✔
916

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

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

937
        return link, nil
415✔
938
}
939

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

307✔
955
        attemptID := pkt.incomingHTLCID
307✔
956

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

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

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

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

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

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

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

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

304✔
1021
        switch htlc := n.msg.(type) {
304✔
1022

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

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

127✔
1040
                return &PaymentResult{
127✔
1041
                        Error: paymentErr,
127✔
1042
                }, nil
127✔
1043

1044
        default:
×
1045
                return nil, fmt.Errorf("received unknown response type: %T",
×
1046
                        htlc)
×
1047
        }
1048
}
1049

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

127✔
1061
        switch {
127✔
1062

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

×
1080
                        log.Errorf("%v: (hash=%v, pid=%d): %v",
×
1081
                                linkError.FailureDetail.FailureString(),
×
1082
                                paymentHash, attemptID, err)
×
1083

×
1084
                        return linkError
×
1085
                }
×
1086

1087
                // If we successfully decoded the failure reason, return it.
1088
                return NewLinkError(failureMsg)
6✔
1089

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

3✔
1100
                log.Infof("%v: hash=%v, pid=%d",
3✔
1101
                        linkError.FailureDetail.FailureString(),
3✔
1102
                        paymentHash, attemptID)
3✔
1103

3✔
1104
                return linkError
3✔
1105

1106
        // A regular multi-hop payment error that we'll need to
1107
        // decrypt.
1108
        default:
122✔
1109
                // We'll attempt to fully decrypt the onion encrypted
122✔
1110
                // error. If we're unable to then we'll bail early.
122✔
1111
                failure, err := deobfuscator.DecryptError(htlc.Reason)
122✔
1112
                if err != nil {
123✔
1113
                        log.Errorf("unable to de-obfuscate onion failure "+
1✔
1114
                                "(hash=%v, pid=%d): %v",
1✔
1115
                                paymentHash, attemptID, err)
1✔
1116

1✔
1117
                        return ErrUnreadableFailureMessage
1✔
1118
                }
1✔
1119

1120
                return failure
121✔
1121
        }
1122
}
1123

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

1135
        case *lnwire.UpdateFulfillHTLC:
403✔
1136
                return s.handlePacketSettle(packet)
403✔
1137

1138
        // Channel link forwarded us an update_fail_htlc message.
1139
        //
1140
        // NOTE: when the channel link receives an update_fail_malformed_htlc
1141
        // from upstream, it will convert the message into update_fail_htlc and
1142
        // forward it. Thus there's no need to catch `UpdateFailMalformedHTLC`
1143
        // here.
1144
        case *lnwire.UpdateFailHTLC:
141✔
1145
                return s.handlePacketFail(packet, htlc)
141✔
1146

1147
        default:
×
1148
                return fmt.Errorf("wrong update type: %T", htlc)
×
1149
        }
1150
}
1151

1152
// checkCircularForward checks whether a forward is circular (arrives and
1153
// departs on the same link) and returns a link error if the switch is
1154
// configured to disallow this behaviour.
1155
func (s *Switch) checkCircularForward(incoming, outgoing lnwire.ShortChannelID,
1156
        allowCircular bool, paymentHash lntypes.Hash) *LinkError {
93✔
1157

93✔
1158
        log.Tracef("Checking for circular route: incoming=%v, outgoing=%v "+
93✔
1159
                "(payment hash: %x)", incoming, outgoing, paymentHash[:])
93✔
1160

93✔
1161
        // If they are equal, we can skip the alias mapping checks.
93✔
1162
        if incoming == outgoing {
97✔
1163
                // The switch may be configured to allow circular routes, so
4✔
1164
                // just log and return nil.
4✔
1165
                if allowCircular {
6✔
1166
                        log.Debugf("allowing circular route over link: %v "+
2✔
1167
                                "(payment hash: %x)", incoming, paymentHash)
2✔
1168
                        return nil
2✔
1169
                }
2✔
1170

1171
                // Otherwise, we'll return a temporary channel failure.
1172
                return NewDetailedLinkError(
2✔
1173
                        lnwire.NewTemporaryChannelFailure(nil),
2✔
1174
                        OutgoingFailureCircularRoute,
2✔
1175
                )
2✔
1176
        }
1177

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

1191
        outgoingBaseScid, ok := s.baseIndex[outgoing]
9✔
1192
        if !ok {
14✔
1193
                // This channel does not use baseIndex, bail out.
5✔
1194
                s.indexMtx.RUnlock()
5✔
1195
                return nil
5✔
1196
        }
5✔
1197
        s.indexMtx.RUnlock()
7✔
1198

7✔
1199
        // Check base SCID equality.
7✔
1200
        if incomingBaseScid != outgoingBaseScid {
10✔
1201
                log.Tracef("Incoming base SCID %v does not match outgoing "+
3✔
1202
                        "base SCID %v (payment hash: %x)", incomingBaseScid,
3✔
1203
                        outgoingBaseScid, paymentHash[:])
3✔
1204

3✔
1205
                // The base SCIDs are not equal so these are not the same
3✔
1206
                // channel.
3✔
1207
                return nil
3✔
1208
        }
3✔
1209

1210
        // If the incoming and outgoing link are equal, the htlc is part of a
1211
        // circular route which may be used to lock up our liquidity. If the
1212
        // switch is configured to allow circular routes, log that we are
1213
        // allowing the route then return nil.
1214
        if allowCircular {
6✔
1215
                log.Debugf("allowing circular route over link: %v "+
2✔
1216
                        "(payment hash: %x)", incoming, paymentHash)
2✔
1217
                return nil
2✔
1218
        }
2✔
1219

1220
        // If our node disallows circular routes, return a temporary channel
1221
        // failure. There is nothing wrong with the policy used by the remote
1222
        // node, so we do not include a channel update.
1223
        return NewDetailedLinkError(
2✔
1224
                lnwire.NewTemporaryChannelFailure(nil),
2✔
1225
                OutgoingFailureCircularRoute,
2✔
1226
        )
2✔
1227
}
1228

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

1244
        log.Error(failure.Error())
29✔
1245

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

29✔
1267
        // Route a fail packet back to the source link.
29✔
1268
        err = s.mailOrchestrator.Deliver(failPkt.incomingChanID, failPkt)
29✔
1269
        if err != nil {
29✔
1270
                err = fmt.Errorf("source chanid=%v unable to "+
×
1271
                        "handle switch packet: %v",
×
1272
                        packet.incomingChanID, err)
×
1273
                log.Error(err)
×
1274
                return err
×
1275
        }
×
1276

1277
        return failure
29✔
1278
}
1279

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

1292
                // Circuit successfully closed.
1293
                case nil:
12✔
1294
                        return circuit, nil
12✔
1295

1296
                // Circuit was previously closed, but has not been deleted.
1297
                // We'll just drop this response until the circuit has been
1298
                // fully removed.
1299
                case ErrCircuitClosing:
×
1300
                        return nil, err
×
1301

1302
                // Failed to close circuit because it does not exist. This is
1303
                // likely because the circuit was already successfully closed.
1304
                // Since this packet failed locally, there is no forwarding
1305
                // package entry to acknowledge.
1306
                case ErrUnknownCircuit:
×
1307
                        return nil, err
×
1308

1309
                // Unexpected error.
1310
                default:
×
1311
                        return nil, err
×
1312
                }
1313
        }
1314

1315
        // Otherwise, this is packet was received from the remote party.  Use
1316
        // circuit map to find the incoming link to receive the settle/fail.
1317
        circuit, err := s.circuits.CloseCircuit(pkt.outKey())
530✔
1318
        switch err {
530✔
1319

1320
        // Open circuit successfully closed.
1321
        case nil:
339✔
1322
                pkt.incomingChanID = circuit.Incoming.ChanID
339✔
1323
                pkt.incomingHTLCID = circuit.Incoming.HtlcID
339✔
1324
                pkt.circuit = circuit
339✔
1325
                pkt.sourceRef = &circuit.AddRef
339✔
1326

339✔
1327
                pktType := "SETTLE"
339✔
1328
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
469✔
1329
                        pktType = "FAIL"
130✔
1330
                }
130✔
1331

1332
                log.Debugf("Closed completed %s circuit for %x: "+
339✔
1333
                        "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
339✔
1334
                        pkt.incomingChanID, pkt.incomingHTLCID,
339✔
1335
                        pkt.outgoingChanID, pkt.outgoingHTLCID)
339✔
1336

339✔
1337
                return circuit, nil
339✔
1338

1339
        // Circuit was previously closed, but has not been deleted. We'll just
1340
        // drop this response until the circuit has been removed.
1341
        case ErrCircuitClosing:
3✔
1342
                return nil, err
3✔
1343

1344
        // Failed to close circuit because it does not exist. This is likely
1345
        // because the circuit was already successfully closed.
1346
        case ErrUnknownCircuit:
194✔
1347
                if pkt.destRef != nil {
387✔
1348
                        // Add this SettleFailRef to the set of pending settle/fail entries
193✔
1349
                        // awaiting acknowledgement.
193✔
1350
                        s.pendingSettleFails = append(s.pendingSettleFails, *pkt.destRef)
193✔
1351
                }
193✔
1352

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

×
1365
                        return nil, err
×
1366
                }
×
1367

1368
                return nil, nil
194✔
1369

1370
        // Unexpected error.
1371
        default:
×
1372
                return nil, err
×
1373
        }
1374
}
1375

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

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

1399
        var paymentHash lntypes.Hash
317✔
1400

317✔
1401
        // Perform a defensive check to make sure we don't try to access a nil
317✔
1402
        // circuit.
317✔
1403
        circuit := pkt.circuit
317✔
1404
        if circuit != nil {
634✔
1405
                copy(paymentHash[:], circuit.PaymentHash[:])
317✔
1406
        }
317✔
1407

1408
        log.Debugf("Tearing down circuit with %s pkt, removing circuit=%v "+
317✔
1409
                "with keystone=%v", pktType, pkt.inKey(), pkt.outKey())
317✔
1410

317✔
1411
        err := s.circuits.DeleteCircuits(pkt.inKey())
317✔
1412
        if err != nil {
317✔
1413
                log.Warnf("Failed to tear down circuit (%s, %d) <-> (%s, %d) "+
×
1414
                        "with payment_hash=%v using %s pkt", pkt.incomingChanID,
×
1415
                        pkt.incomingHTLCID, pkt.outgoingChanID,
×
1416
                        pkt.outgoingHTLCID, pkt.circuit.PaymentHash, pktType)
×
1417

×
1418
                return err
×
1419
        }
×
1420

1421
        log.Debugf("Closed %s circuit for %v: (%s, %d) <-> (%s, %d)", pktType,
317✔
1422
                paymentHash, pkt.incomingChanID, pkt.incomingHTLCID,
317✔
1423
                pkt.outgoingChanID, pkt.outgoingHTLCID)
317✔
1424

317✔
1425
        return nil
317✔
1426
}
1427

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

3✔
1438
        // TODO(roasbeef) abstract out the close updates.
3✔
1439
        updateChan := make(chan interface{}, 2)
3✔
1440
        errChan := make(chan error, 1)
3✔
1441

3✔
1442
        command := &ChanClose{
3✔
1443
                CloseType:      closeType,
3✔
1444
                ChanPoint:      chanPoint,
3✔
1445
                Updates:        updateChan,
3✔
1446
                TargetFeePerKw: targetFeePerKw,
3✔
1447
                DeliveryScript: deliveryScript,
3✔
1448
                Err:            errChan,
3✔
1449
                MaxFee:         maxFee,
3✔
1450
                Ctx:            ctx,
3✔
1451
        }
3✔
1452

3✔
1453
        select {
3✔
1454
        case s.chanCloseRequests <- command:
3✔
1455
                return updateChan, errChan
3✔
1456

1457
        case <-s.quit:
×
1458
                errChan <- ErrSwitchExiting
×
1459
                close(updateChan)
×
1460
                return updateChan, errChan
×
1461
        }
1462
}
1463

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

210✔
1477
        defer func() {
420✔
1478
                s.blockEpochStream.Cancel()
210✔
1479

210✔
1480
                // Remove all links once we've been signalled for shutdown.
210✔
1481
                var linksToStop []ChannelLink
210✔
1482
                s.indexMtx.Lock()
210✔
1483
                for _, link := range s.linkIndex {
505✔
1484
                        activeLink := s.removeLink(link.ChanID())
295✔
1485
                        if activeLink == nil {
295✔
1486
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1487
                                        "on stop", link.ChanID())
×
1488
                                continue
×
1489
                        }
1490
                        linksToStop = append(linksToStop, activeLink)
295✔
1491
                }
1492
                for _, link := range s.pendingLinkIndex {
214✔
1493
                        pendingLink := s.removeLink(link.ChanID())
4✔
1494
                        if pendingLink == nil {
4✔
1495
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1496
                                        "on stop", link.ChanID())
×
1497
                                continue
×
1498
                        }
1499
                        linksToStop = append(linksToStop, pendingLink)
4✔
1500
                }
1501
                s.indexMtx.Unlock()
210✔
1502

210✔
1503
                // Now that all pending and live links have been removed from
210✔
1504
                // the forwarding indexes, stop each one before shutting down.
210✔
1505
                // We'll shut them down in parallel to make exiting as fast as
210✔
1506
                // possible.
210✔
1507
                var wg sync.WaitGroup
210✔
1508
                for _, link := range linksToStop {
506✔
1509
                        wg.Add(1)
296✔
1510
                        go func(l ChannelLink) {
592✔
1511
                                defer wg.Done()
296✔
1512

296✔
1513
                                l.Stop()
296✔
1514
                        }(link)
296✔
1515
                }
1516
                wg.Wait()
210✔
1517

210✔
1518
                // Before we exit fully, we'll attempt to flush out any
210✔
1519
                // forwarding events that may still be lingering since the last
210✔
1520
                // batch flush.
210✔
1521
                if err := s.FlushForwardingEvents(); err != nil {
210✔
1522
                        log.Errorf("unable to flush forwarding events: %v", err)
×
1523
                }
×
1524
        }()
1525

1526
        // TODO(roasbeef): cleared vs settled distinction
1527
        var (
210✔
1528
                totalNumUpdates uint64
210✔
1529
                totalSatSent    btcutil.Amount
210✔
1530
                totalSatRecv    btcutil.Amount
210✔
1531
        )
210✔
1532
        s.cfg.LogEventTicker.Resume()
210✔
1533
        defer s.cfg.LogEventTicker.Stop()
210✔
1534

210✔
1535
        // Every 15 seconds, we'll flush out the forwarding events that
210✔
1536
        // occurred during that period.
210✔
1537
        s.cfg.FwdEventTicker.Resume()
210✔
1538
        defer s.cfg.FwdEventTicker.Stop()
210✔
1539

210✔
1540
        defer s.cfg.AckEventTicker.Stop()
210✔
1541

210✔
1542
out:
210✔
1543
        for {
1,046✔
1544

836✔
1545
                // If the set of pending settle/fail entries is non-zero,
836✔
1546
                // reinstate the ack ticker so we can batch ack them.
836✔
1547
                if len(s.pendingSettleFails) > 0 {
1,217✔
1548
                        s.cfg.AckEventTicker.Resume()
381✔
1549
                }
381✔
1550

1551
                select {
836✔
1552
                case blockEpoch, ok := <-s.blockEpochStream.Epochs:
3✔
1553
                        if !ok {
3✔
1554
                                break out
×
1555
                        }
1556

1557
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
3✔
1558

1559
                // A local close request has arrived, we'll forward this to the
1560
                // relevant link (if it exists) so the channel can be
1561
                // cooperatively closed (if possible).
1562
                case req := <-s.chanCloseRequests:
3✔
1563
                        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
3✔
1564

3✔
1565
                        s.indexMtx.RLock()
3✔
1566
                        link, ok := s.linkIndex[chanID]
3✔
1567
                        if !ok {
6✔
1568
                                s.indexMtx.RUnlock()
3✔
1569

3✔
1570
                                req.Err <- fmt.Errorf("no peer for channel with "+
3✔
1571
                                        "chan_id=%x", chanID[:])
3✔
1572
                                continue
3✔
1573
                        }
1574
                        s.indexMtx.RUnlock()
3✔
1575

3✔
1576
                        peerPub := link.PeerPubKey()
3✔
1577
                        log.Debugf("Requesting local channel close: peer=%x, "+
3✔
1578
                                "chan_id=%x", link.PeerPubKey(), chanID[:])
3✔
1579

3✔
1580
                        go s.cfg.LocalChannelClose(peerPub[:], req)
3✔
1581

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

1599
                        // At this point, the resolution message has been
1600
                        // persisted. It is safe to signal success by sending
1601
                        // a nil error since the Switch will re-deliver the
1602
                        // resolution message on restart.
1603
                        resolutionMsg.errChan <- nil
4✔
1604

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

4✔
1615
                        // Resolution messages will either be cancelling
4✔
1616
                        // backwards an existing HTLC, or settling a previously
4✔
1617
                        // outgoing HTLC. Based on this, we'll map the message
4✔
1618
                        // to the proper htlcPacket.
4✔
1619
                        if resolutionMsg.Failure != nil {
7✔
1620
                                pkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1621
                        } else {
7✔
1622
                                pkt.htlc = &lnwire.UpdateFulfillHTLC{
4✔
1623
                                        PaymentPreimage: *resolutionMsg.PreImage,
4✔
1624
                                }
4✔
1625
                        }
4✔
1626

1627
                        log.Debugf("Received outside contract resolution, "+
4✔
1628
                                "mapping to: %v", spew.Sdump(pkt))
4✔
1629

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

1639
                // A new packet has arrived for forwarding, we'll interpret the
1640
                // packet concretely, then either forward it along, or
1641
                // interpret a return packet to a locally initialized one.
1642
                case cmd := <-s.htlcPlex:
622✔
1643
                        cmd.err <- s.handlePacketForward(cmd.pkt)
622✔
1644

1645
                // When this time ticks, then it indicates that we should
1646
                // collect all the forwarding events since the last internal,
1647
                // and write them out to our log.
1648
                case <-s.cfg.FwdEventTicker.Ticks():
5✔
1649
                        s.wg.Add(1)
5✔
1650
                        go func() {
10✔
1651
                                defer s.wg.Done()
5✔
1652

5✔
1653
                                if err := s.FlushForwardingEvents(); err != nil {
5✔
1654
                                        log.Errorf("Unable to flush "+
×
1655
                                                "forwarding events: %v", err)
×
1656
                                }
×
1657
                        }()
1658

1659
                // The log ticker has fired, so we'll calculate some forwarding
1660
                // stats for the last 10 seconds to display within the logs to
1661
                // users.
1662
                case <-s.cfg.LogEventTicker.Ticks():
7✔
1663
                        // First, we'll collate the current running tally of
7✔
1664
                        // our forwarding stats.
7✔
1665
                        prevSatSent := totalSatSent
7✔
1666
                        prevSatRecv := totalSatRecv
7✔
1667
                        prevNumUpdates := totalNumUpdates
7✔
1668

7✔
1669
                        var (
7✔
1670
                                newNumUpdates uint64
7✔
1671
                                newSatSent    btcutil.Amount
7✔
1672
                                newSatRecv    btcutil.Amount
7✔
1673
                        )
7✔
1674

7✔
1675
                        // Next, we'll run through all the registered links and
7✔
1676
                        // compute their up-to-date forwarding stats.
7✔
1677
                        s.indexMtx.RLock()
7✔
1678
                        for _, link := range s.linkIndex {
16✔
1679
                                // TODO(roasbeef): when links first registered
9✔
1680
                                // stats printed.
9✔
1681
                                updates, sent, recv := link.Stats()
9✔
1682
                                newNumUpdates += updates
9✔
1683
                                newSatSent += sent.ToSatoshis()
9✔
1684
                                newSatRecv += recv.ToSatoshis()
9✔
1685
                        }
9✔
1686
                        s.indexMtx.RUnlock()
7✔
1687

7✔
1688
                        var (
7✔
1689
                                diffNumUpdates uint64
7✔
1690
                                diffSatSent    btcutil.Amount
7✔
1691
                                diffSatRecv    btcutil.Amount
7✔
1692
                        )
7✔
1693

7✔
1694
                        // If this is the first time we're computing these
7✔
1695
                        // stats, then the diff is just the new value. We do
7✔
1696
                        // this in order to avoid integer underflow issues.
7✔
1697
                        if prevNumUpdates == 0 {
14✔
1698
                                diffNumUpdates = newNumUpdates
7✔
1699
                                diffSatSent = newSatSent
7✔
1700
                                diffSatRecv = newSatRecv
7✔
1701
                        } else {
10✔
1702
                                diffNumUpdates = newNumUpdates - prevNumUpdates
3✔
1703
                                diffSatSent = newSatSent - prevSatSent
3✔
1704
                                diffSatRecv = newSatRecv - prevSatRecv
3✔
1705
                        }
3✔
1706

1707
                        // If the diff of num updates is zero, then we haven't
1708
                        // forwarded anything in the last 10 seconds, so we can
1709
                        // skip this update.
1710
                        if diffNumUpdates == 0 {
12✔
1711
                                continue
5✔
1712
                        }
1713

1714
                        // If the diff of num updates is negative, then some
1715
                        // links may have been unregistered from the switch, so
1716
                        // we'll update our stats to only include our registered
1717
                        // links.
1718
                        if int64(diffNumUpdates) < 0 {
8✔
1719
                                totalNumUpdates = newNumUpdates
3✔
1720
                                totalSatSent = newSatSent
3✔
1721
                                totalSatRecv = newSatRecv
3✔
1722
                                continue
3✔
1723
                        }
1724

1725
                        // Otherwise, we'll log this diff, then accumulate the
1726
                        // new stats into the running total.
1727
                        log.Debugf("Sent %d satoshis and received %d satoshis "+
5✔
1728
                                "in the last 10 seconds (%f tx/sec)",
5✔
1729
                                diffSatSent, diffSatRecv,
5✔
1730
                                float64(diffNumUpdates)/10)
5✔
1731

5✔
1732
                        totalNumUpdates += diffNumUpdates
5✔
1733
                        totalSatSent += diffSatSent
5✔
1734
                        totalSatRecv += diffSatRecv
5✔
1735

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

1746
                        // Batch ack the settle/fail entries.
1747
                        if err := s.ackSettleFail(s.pendingSettleFails...); err != nil {
3✔
1748
                                log.Errorf("Unable to ack batch of settle/fails: %v", err)
×
1749
                                continue
×
1750
                        }
1751

1752
                        log.Tracef("Acked %d settle fails: %v",
3✔
1753
                                len(s.pendingSettleFails),
3✔
1754
                                lnutils.SpewLogClosure(s.pendingSettleFails))
3✔
1755

3✔
1756
                        // Reset the pendingSettleFails buffer while keeping acquired
3✔
1757
                        // memory.
3✔
1758
                        s.pendingSettleFails = s.pendingSettleFails[:0]
3✔
1759

1760
                case <-s.quit:
210✔
1761
                        return
210✔
1762
                }
1763
        }
1764
}
1765

1766
// Start starts all helper goroutines required for the operation of the switch.
1767
func (s *Switch) Start() error {
210✔
1768
        if !atomic.CompareAndSwapInt32(&s.started, 0, 1) {
210✔
1769
                log.Warn("Htlc Switch already started")
×
1770
                return errors.New("htlc switch already started")
×
1771
        }
×
1772

1773
        log.Infof("HTLC Switch starting")
210✔
1774

210✔
1775
        blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
210✔
1776
        if err != nil {
210✔
1777
                return err
×
1778
        }
×
1779
        s.blockEpochStream = blockEpochStream
210✔
1780

210✔
1781
        s.wg.Add(1)
210✔
1782
        go s.htlcForwarder()
210✔
1783

210✔
1784
        if err := s.reforwardResponses(); err != nil {
210✔
1785
                s.Stop()
×
1786
                log.Errorf("unable to reforward responses: %v", err)
×
1787
                return err
×
1788
        }
×
1789

1790
        if err := s.reforwardResolutions(); err != nil {
210✔
1791
                // We are already stopping so we can ignore the error.
×
1792
                _ = s.Stop()
×
1793
                log.Errorf("unable to reforward resolutions: %v", err)
×
1794
                return err
×
1795
        }
×
1796

1797
        return nil
210✔
1798
}
1799

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

1811
        switchPackets := make([]*htlcPacket, 0, len(resMsgs))
210✔
1812
        for _, resMsg := range resMsgs {
214✔
1813
                // If the open circuit no longer exists, then we can remove the
4✔
1814
                // message from the store.
4✔
1815
                outKey := CircuitKey{
4✔
1816
                        ChanID: resMsg.SourceChan,
4✔
1817
                        HtlcID: resMsg.HtlcIndex,
4✔
1818
                }
4✔
1819

4✔
1820
                if s.circuits.LookupOpenCircuit(outKey) == nil {
8✔
1821
                        // The open circuit doesn't exist.
4✔
1822
                        err := s.resMsgStore.deleteResolutionMsg(&outKey)
4✔
1823
                        if err != nil {
4✔
1824
                                return err
×
1825
                        }
×
1826

1827
                        continue
4✔
1828
                }
1829

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

3✔
1840
                if resMsg.Failure != nil {
6✔
1841
                        resPkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1842
                } else {
3✔
1843
                        resPkt.htlc = &lnwire.UpdateFulfillHTLC{
×
1844
                                PaymentPreimage: *resMsg.PreImage,
×
1845
                        }
×
1846
                }
×
1847

1848
                switchPackets = append(switchPackets, resPkt)
3✔
1849
        }
1850

1851
        // We'll now dispatch the set of resolution messages to the proper
1852
        // destination. An error is only encountered here if the switch is
1853
        // shutting down.
1854
        if err := s.ForwardPackets(nil, switchPackets...); err != nil {
210✔
1855
                return err
×
1856
        }
×
1857

1858
        return nil
210✔
1859
}
1860

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

1872
        for _, openChannel := range openChannels {
342✔
1873
                shortChanID := openChannel.ShortChanID()
132✔
1874

132✔
1875
                // Locally-initiated payments never need reforwarding.
132✔
1876
                if shortChanID == hop.Source {
135✔
1877
                        continue
3✔
1878
                }
1879

1880
                // If the channel is pending, it should have no forwarding
1881
                // packages, and nothing to reforward.
1882
                if openChannel.IsPending {
132✔
1883
                        continue
×
1884
                }
1885

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

1899
                s.reforwardSettleFails(fwdPkgs)
132✔
1900
        }
1901

1902
        return nil
210✔
1903
}
1904

1905
// loadChannelFwdPkgs loads all forwarding packages owned by the `source` short
1906
// channel identifier.
1907
func (s *Switch) loadChannelFwdPkgs(source lnwire.ShortChannelID) ([]*channeldb.FwdPkg, error) {
132✔
1908

132✔
1909
        var fwdPkgs []*channeldb.FwdPkg
132✔
1910
        if err := kvdb.View(s.cfg.DB, func(tx kvdb.RTx) error {
264✔
1911
                var err error
132✔
1912
                fwdPkgs, err = s.cfg.SwitchPackager.LoadChannelFwdPkgs(
132✔
1913
                        tx, source,
132✔
1914
                )
132✔
1915
                return err
132✔
1916
        }, func() {
264✔
1917
                fwdPkgs = nil
132✔
1918
        }); err != nil {
132✔
1919
                return nil, err
×
1920
        }
×
1921

1922
        return fwdPkgs, nil
132✔
1923
}
1924

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

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

3✔
1957
                                // Add the packet to the batch to be forwarded, and
3✔
1958
                                // notify the overflow queue that a spare spot has been
3✔
1959
                                // freed up within the commitment state.
3✔
1960
                                switchPackets = append(switchPackets, settlePacket)
3✔
1961

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

×
1984
                                // Add the packet to the batch to be forwarded, and
×
1985
                                // notify the overflow queue that a spare spot has been
×
1986
                                // freed up within the commitment state.
×
1987
                                switchPackets = append(switchPackets, failPacket)
×
1988
                        }
1989
                }
1990

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

2001
// Stop gracefully stops all active helper goroutines, then waits until they've
2002
// exited.
2003
func (s *Switch) Stop() error {
442✔
2004
        if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
572✔
2005
                log.Warn("Htlc Switch already stopped")
130✔
2006
                return errors.New("htlc switch already shutdown")
130✔
2007
        }
130✔
2008

2009
        log.Info("HTLC Switch shutting down...")
312✔
2010
        defer log.Debug("HTLC Switch shutdown complete")
312✔
2011

312✔
2012
        close(s.quit)
312✔
2013

312✔
2014
        s.wg.Wait()
312✔
2015

312✔
2016
        // Wait until all active goroutines have finished exiting before
312✔
2017
        // stopping the mailboxes, otherwise the mailbox map could still be
312✔
2018
        // accessed and modified.
312✔
2019
        s.mailOrchestrator.Stop()
312✔
2020

312✔
2021
        return nil
312✔
2022
}
2023

2024
// CreateAndAddLink will create a link and then add it to the internal maps
2025
// when given a ChannelLinkConfig and LightningChannel.
2026
func (s *Switch) CreateAndAddLink(linkCfg ChannelLinkConfig,
2027
        lnChan *lnwallet.LightningChannel) error {
3✔
2028

3✔
2029
        link := NewChannelLink(linkCfg, lnChan)
3✔
2030
        return s.AddLink(link)
3✔
2031
}
3✔
2032

2033
// AddLink is used to initiate the handling of the add link command. The
2034
// request will be propagated and handled in the main goroutine.
2035
func (s *Switch) AddLink(link ChannelLink) error {
339✔
2036
        s.indexMtx.Lock()
339✔
2037
        defer s.indexMtx.Unlock()
339✔
2038

339✔
2039
        chanID := link.ChanID()
339✔
2040

339✔
2041
        // First, ensure that this link is not already active in the switch.
339✔
2042
        _, err := s.getLink(chanID)
339✔
2043
        if err == nil {
340✔
2044
                return fmt.Errorf("unable to add ChannelLink(%v), already "+
1✔
2045
                        "active", chanID)
1✔
2046
        }
1✔
2047

2048
        // Get and attach the mailbox for this link, which buffers packets in
2049
        // case there packets that we tried to deliver while this link was
2050
        // offline.
2051
        shortChanID := link.ShortChanID()
338✔
2052
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(chanID, shortChanID)
338✔
2053
        link.AttachMailBox(mailbox)
338✔
2054

338✔
2055
        // Attach the Switch's failAliasUpdate function to the link.
338✔
2056
        link.attachFailAliasUpdate(s.failAliasUpdate)
338✔
2057

338✔
2058
        if err := link.Start(); err != nil {
338✔
2059
                log.Errorf("AddLink failed to start link with chanID=%v: %v",
×
2060
                        chanID, err)
×
2061
                s.removeLink(chanID)
×
2062
                return err
×
2063
        }
×
2064

2065
        if shortChanID == hop.Source {
342✔
2066
                log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
4✔
2067
                        chanID, shortChanID)
4✔
2068

4✔
2069
                s.pendingLinkIndex[chanID] = link
4✔
2070
        } else {
341✔
2071
                log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
337✔
2072
                        chanID, shortChanID)
337✔
2073

337✔
2074
                s.addLiveLink(link)
337✔
2075
                s.mailOrchestrator.BindLiveShortChanID(
337✔
2076
                        mailbox, chanID, shortChanID,
337✔
2077
                )
337✔
2078
        }
337✔
2079

2080
        return nil
338✔
2081
}
2082

2083
// addLiveLink adds a link to all associated forwarding index, this makes it a
2084
// candidate for forwarding HTLCs.
2085
func (s *Switch) addLiveLink(link ChannelLink) {
337✔
2086
        linkScid := link.ShortChanID()
337✔
2087

337✔
2088
        // We'll add the link to the linkIndex which lets us quickly
337✔
2089
        // look up a channel when we need to close or register it, and
337✔
2090
        // the forwarding index which'll be used when forwarding HTLC's
337✔
2091
        // in the multi-hop setting.
337✔
2092
        s.linkIndex[link.ChanID()] = link
337✔
2093
        s.forwardingIndex[linkScid] = link
337✔
2094

337✔
2095
        // Next we'll add the link to the interface index so we can
337✔
2096
        // quickly look up all the channels for a particular node.
337✔
2097
        peerPub := link.PeerPubKey()
337✔
2098
        if _, ok := s.interfaceIndex[peerPub]; !ok {
669✔
2099
                s.interfaceIndex[peerPub] = make(map[lnwire.ChannelID]ChannelLink)
332✔
2100
        }
332✔
2101
        s.interfaceIndex[peerPub][link.ChanID()] = link
337✔
2102

337✔
2103
        s.updateLinkAliases(link)
337✔
2104
}
2105

2106
// UpdateLinkAliases is the externally exposed wrapper for updating link
2107
// aliases. It acquires the indexMtx and calls the internal method.
2108
func (s *Switch) UpdateLinkAliases(link ChannelLink) {
3✔
2109
        s.indexMtx.Lock()
3✔
2110
        defer s.indexMtx.Unlock()
3✔
2111

3✔
2112
        s.updateLinkAliases(link)
3✔
2113
}
3✔
2114

2115
// updateLinkAliases updates the aliases for a given link. This will cause the
2116
// htlcswitch to consult the alias manager on the up to date values of its
2117
// alias maps.
2118
//
2119
// NOTE: this MUST be called with the indexMtx held.
2120
func (s *Switch) updateLinkAliases(link ChannelLink) {
337✔
2121
        linkScid := link.ShortChanID()
337✔
2122

337✔
2123
        aliases := link.getAliases()
337✔
2124
        if link.isZeroConf() {
359✔
2125
                if link.zeroConfConfirmed() {
40✔
2126
                        // Since the zero-conf channel has confirmed, we can
18✔
2127
                        // populate the aliasToReal mapping.
18✔
2128
                        confirmedScid := link.confirmedScid()
18✔
2129

18✔
2130
                        for _, alias := range aliases {
43✔
2131
                                s.aliasToReal[alias] = confirmedScid
25✔
2132
                        }
25✔
2133

2134
                        // Add the confirmed SCID as a key in the baseIndex.
2135
                        s.baseIndex[confirmedScid] = linkScid
18✔
2136
                }
2137

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

2156
                for alias, real := range s.baseIndex {
25✔
2157
                        if real == linkScid {
9✔
2158
                                delete(s.baseIndex, alias)
3✔
2159
                        }
3✔
2160
                }
2161

2162
                // The link's SCID is the confirmed SCID for non-zero-conf
2163
                // option-scid-alias feature bit channels.
2164
                for _, alias := range aliases {
45✔
2165
                        s.aliasToReal[alias] = linkScid
26✔
2166
                        s.baseIndex[alias] = linkScid
26✔
2167
                }
26✔
2168

2169
                // Since the link's SCID is confirmed, it was not included in
2170
                // the baseIndex above as a key. Add it now.
2171
                s.baseIndex[linkScid] = linkScid
19✔
2172
        }
2173
}
2174

2175
// GetLink is used to initiate the handling of the get link command. The
2176
// request will be propagated/handled to/in the main goroutine.
2177
func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelUpdateHandler,
2178
        error) {
3,200✔
2179

3,200✔
2180
        s.indexMtx.RLock()
3,200✔
2181
        defer s.indexMtx.RUnlock()
3,200✔
2182

3,200✔
2183
        return s.getLink(chanID)
3,200✔
2184
}
3,200✔
2185

2186
// getLink returns the link stored in either the pending index or the live
2187
// lindex.
2188
func (s *Switch) getLink(chanID lnwire.ChannelID) (ChannelLink, error) {
3,865✔
2189
        link, ok := s.linkIndex[chanID]
3,865✔
2190
        if !ok {
4,204✔
2191
                link, ok = s.pendingLinkIndex[chanID]
339✔
2192
                if !ok {
677✔
2193
                        return nil, ErrChannelLinkNotFound
338✔
2194
                }
338✔
2195
        }
2196

2197
        return link, nil
3,530✔
2198
}
2199

2200
// GetLinkByShortID attempts to return the link which possesses the target short
2201
// channel ID.
2202
func (s *Switch) GetLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink,
2203
        error) {
3✔
2204

3✔
2205
        s.indexMtx.RLock()
3✔
2206
        defer s.indexMtx.RUnlock()
3✔
2207

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

2218
                // An alias was found, use it to lookup if a link exists.
2219
                return s.getLinkByShortID(aliasID)
3✔
2220
        }
2221

2222
        return link, nil
3✔
2223
}
2224

2225
// getLinkByShortID attempts to return the link which possesses the target
2226
// short channel ID.
2227
//
2228
// NOTE: This MUST be called with the indexMtx held.
2229
func (s *Switch) getLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink, error) {
480✔
2230
        link, ok := s.forwardingIndex[chanID]
480✔
2231
        if !ok {
484✔
2232
                log.Debugf("Link not found in forwarding index using "+
4✔
2233
                        "chanID=%v", chanID)
4✔
2234

4✔
2235
                return nil, ErrChannelLinkNotFound
4✔
2236
        }
4✔
2237

2238
        return link, nil
479✔
2239
}
2240

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

83✔
2262
        log.Debugf("Querying outgoing link using chanID=%v, aliasID=%v", chanID,
83✔
2263
                aliasID)
83✔
2264

83✔
2265
        // Set the originalOutgoingChanID so the proper channel_update can be
83✔
2266
        // sent back if the option-scid-alias feature bit was negotiated.
83✔
2267
        pkt.originalOutgoingChanID = chanID
83✔
2268

83✔
2269
        if aliasID {
101✔
2270
                // Since outgoingChanID is an alias, we'll fetch the link via
18✔
2271
                // baseIndex.
18✔
2272
                baseScid, ok := s.baseIndex[chanID]
18✔
2273
                if !ok {
18✔
2274
                        // No mapping exists, bail.
×
2275
                        return nil, ErrChannelLinkNotFound
×
2276
                }
×
2277

2278
                // A mapping exists, so use baseScid to find the link in the
2279
                // forwardingIndex.
2280
                link, ok := s.forwardingIndex[baseScid]
18✔
2281
                if !ok {
18✔
2282
                        log.Debugf("Forwarding index not found using "+
×
2283
                                "baseScid=%v", baseScid)
×
2284

×
2285
                        // Link not found, bail.
×
2286
                        return nil, ErrChannelLinkNotFound
×
2287
                }
×
2288

2289
                // Change the packet's outgoingChanID field so that errors are
2290
                // properly attributed.
2291
                pkt.outgoingChanID = baseScid
18✔
2292

18✔
2293
                // Return the link without checking if it's private or not.
18✔
2294
                return link, nil
18✔
2295
        }
2296

2297
        // The outgoingChanID is a confirmed SCID. Attempt to fetch the base
2298
        // SCID from baseIndex.
2299
        baseScid, ok := s.baseIndex[chanID]
68✔
2300
        if !ok {
129✔
2301
                // outgoingChanID is not a key in base index meaning this
61✔
2302
                // channel did not have the option-scid-alias feature bit
61✔
2303
                // negotiated. We'll fetch the link and return it.
61✔
2304
                link, ok := s.forwardingIndex[chanID]
61✔
2305
                if !ok {
66✔
2306
                        log.Debugf("Forwarding index not found using "+
5✔
2307
                                "chanID=%v", chanID)
5✔
2308

5✔
2309
                        // The link wasn't found, bail out.
5✔
2310
                        return nil, ErrChannelLinkNotFound
5✔
2311
                }
5✔
2312

2313
                return link, nil
59✔
2314
        }
2315

2316
        // Fetch the link whose internal SCID is baseScid.
2317
        link, ok := s.forwardingIndex[baseScid]
10✔
2318
        if !ok {
10✔
2319
                log.Debugf("Forwarding index not found using baseScid=%v",
×
2320
                        baseScid)
×
2321

×
2322
                // Link wasn't found, bail out.
×
2323
                return nil, ErrChannelLinkNotFound
×
2324
        }
×
2325

2326
        // If the link is unadvertised, we fail since the real SCID was used to
2327
        // forward over it and this is a channel where the option-scid-alias
2328
        // feature bit was negotiated.
2329
        if link.IsUnadvertised() {
12✔
2330
                log.Debugf("Link is unadvertised, chanID=%v, baseScid=%v",
2✔
2331
                        chanID, baseScid)
2✔
2332

2✔
2333
                return nil, ErrChannelLinkNotFound
2✔
2334
        }
2✔
2335

2336
        // The link is public so the confirmed SCID can be used to forward over
2337
        // it. We'll also replace pkt's outgoingChanID field so errors can
2338
        // properly be attributed in the calling function.
2339
        pkt.outgoingChanID = baseScid
8✔
2340
        return link, nil
8✔
2341
}
2342

2343
// HasActiveLink returns true if the given channel ID has a link in the link
2344
// index AND the link is eligible to forward.
2345
func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
5✔
2346
        s.indexMtx.RLock()
5✔
2347
        defer s.indexMtx.RUnlock()
5✔
2348

5✔
2349
        if link, ok := s.linkIndex[chanID]; ok {
10✔
2350
                return link.EligibleToForward()
5✔
2351
        }
5✔
2352

2353
        return false
3✔
2354
}
2355

2356
// RemoveLink purges the switch of any link associated with chanID. If a pending
2357
// or active link is not found, this method does nothing. Otherwise, the method
2358
// returns after the link has been completely shutdown.
2359
func (s *Switch) RemoveLink(chanID lnwire.ChannelID) {
21✔
2360
        s.indexMtx.Lock()
21✔
2361
        link, err := s.getLink(chanID)
21✔
2362
        if err != nil {
24✔
2363
                // If err is non-nil, this means that link is also nil. The
3✔
2364
                // link variable cannot be nil without err being non-nil.
3✔
2365
                s.indexMtx.Unlock()
3✔
2366
                log.Tracef("Unable to remove link for ChannelID(%v): %v",
3✔
2367
                        chanID, err)
3✔
2368
                return
3✔
2369
        }
3✔
2370

2371
        // Check if the link is already stopping and grab the stop chan if it
2372
        // is.
2373
        stopChan, ok := s.linkStopIndex[chanID]
21✔
2374
        if !ok {
42✔
2375
                // If the link is non-nil, it is not currently stopping, so
21✔
2376
                // we'll add a stop chan to the linkStopIndex.
21✔
2377
                stopChan = make(chan struct{})
21✔
2378
                s.linkStopIndex[chanID] = stopChan
21✔
2379
        }
21✔
2380
        s.indexMtx.Unlock()
21✔
2381

21✔
2382
        if ok {
21✔
2383
                // If the stop chan exists, we will wait for it to be closed.
×
2384
                // Once it is closed, we will exit.
×
2385
                select {
×
2386
                case <-stopChan:
×
2387
                        return
×
2388
                case <-s.quit:
×
2389
                        return
×
2390
                }
2391
        }
2392

2393
        // Stop the link before removing it from the maps.
2394
        link.Stop()
21✔
2395

21✔
2396
        s.indexMtx.Lock()
21✔
2397
        _ = s.removeLink(chanID)
21✔
2398

21✔
2399
        // Close stopChan and remove this link from the linkStopIndex.
21✔
2400
        // Deleting from the index and removing from the link must be done
21✔
2401
        // in the same block while the mutex is held.
21✔
2402
        close(stopChan)
21✔
2403
        delete(s.linkStopIndex, chanID)
21✔
2404
        s.indexMtx.Unlock()
21✔
2405
}
2406

2407
// removeLink is used to remove and stop the channel link.
2408
//
2409
// NOTE: This MUST be called with the indexMtx held.
2410
func (s *Switch) removeLink(chanID lnwire.ChannelID) ChannelLink {
314✔
2411
        log.Infof("Removing channel link with ChannelID(%v)", chanID)
314✔
2412

314✔
2413
        link, err := s.getLink(chanID)
314✔
2414
        if err != nil {
314✔
2415
                return nil
×
2416
        }
×
2417

2418
        // Remove the channel from live link indexes.
2419
        delete(s.pendingLinkIndex, link.ChanID())
314✔
2420
        delete(s.linkIndex, link.ChanID())
314✔
2421
        delete(s.forwardingIndex, link.ShortChanID())
314✔
2422

314✔
2423
        // If the link has been added to the peer index, then we'll move to
314✔
2424
        // delete the entry within the index.
314✔
2425
        peerPub := link.PeerPubKey()
314✔
2426
        if peerIndex, ok := s.interfaceIndex[peerPub]; ok {
627✔
2427
                delete(peerIndex, link.ChanID())
313✔
2428

313✔
2429
                // If after deletion, there are no longer any links, then we'll
313✔
2430
                // remove the interface map all together.
313✔
2431
                if len(peerIndex) == 0 {
621✔
2432
                        delete(s.interfaceIndex, peerPub)
308✔
2433
                }
308✔
2434
        }
2435

2436
        return link
314✔
2437
}
2438

2439
// UpdateShortChanID locates the link with the passed-in chanID and updates the
2440
// underlying channel state. This is only used in zero-conf channels to allow
2441
// the confirmed SCID to be updated.
2442
func (s *Switch) UpdateShortChanID(chanID lnwire.ChannelID) error {
4✔
2443
        s.indexMtx.Lock()
4✔
2444
        defer s.indexMtx.Unlock()
4✔
2445

4✔
2446
        // Locate the target link in the link index. If no such link exists,
4✔
2447
        // then we will ignore the request.
4✔
2448
        link, ok := s.linkIndex[chanID]
4✔
2449
        if !ok {
4✔
2450
                return fmt.Errorf("link %v not found", chanID)
×
2451
        }
×
2452

2453
        // Try to update the link's underlying channel state, returning early
2454
        // if this update failed.
2455
        _, err := link.UpdateShortChanID()
4✔
2456
        if err != nil {
4✔
2457
                return err
×
2458
        }
×
2459

2460
        // Since the zero-conf channel is confirmed, we should populate the
2461
        // aliasToReal map and update the baseIndex.
2462
        aliases := link.getAliases()
4✔
2463

4✔
2464
        confirmedScid := link.confirmedScid()
4✔
2465

4✔
2466
        for _, alias := range aliases {
9✔
2467
                s.aliasToReal[alias] = confirmedScid
5✔
2468
        }
5✔
2469

2470
        s.baseIndex[confirmedScid] = link.ShortChanID()
4✔
2471

4✔
2472
        return nil
4✔
2473
}
2474

2475
// GetLinksByInterface fetches all the links connected to a particular node
2476
// identified by the serialized compressed form of its public key.
2477
func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
2478
        error) {
3✔
2479

3✔
2480
        s.indexMtx.RLock()
3✔
2481
        defer s.indexMtx.RUnlock()
3✔
2482

3✔
2483
        var handlers []ChannelUpdateHandler
3✔
2484

3✔
2485
        links, err := s.getLinks(hop)
3✔
2486
        if err != nil {
6✔
2487
                return nil, err
3✔
2488
        }
3✔
2489

2490
        // Range over the returned []ChannelLink to convert them into
2491
        // []ChannelUpdateHandler.
2492
        for _, link := range links {
6✔
2493
                handlers = append(handlers, link)
3✔
2494
        }
3✔
2495

2496
        return handlers, nil
3✔
2497
}
2498

2499
// getLinks is function which returns the channel links of the peer by hop
2500
// destination id.
2501
//
2502
// NOTE: This MUST be called with the indexMtx held.
2503
func (s *Switch) getLinks(destination [33]byte) ([]ChannelLink, error) {
79✔
2504
        links, ok := s.interfaceIndex[destination]
79✔
2505
        if !ok {
82✔
2506
                return nil, ErrNoLinksFound
3✔
2507
        }
3✔
2508

2509
        channelLinks := make([]ChannelLink, 0, len(links))
79✔
2510
        for _, link := range links {
162✔
2511
                channelLinks = append(channelLinks, link)
83✔
2512
        }
83✔
2513

2514
        return channelLinks, nil
79✔
2515
}
2516

2517
// CircuitModifier returns a reference to subset of the interfaces provided by
2518
// the circuit map, to allow links to open and close circuits.
2519
func (s *Switch) CircuitModifier() CircuitModifier {
218✔
2520
        return s.circuits
218✔
2521
}
218✔
2522

2523
// CircuitLookup returns a reference to subset of the interfaces provided by the
2524
// circuit map, to allow looking up circuits.
2525
func (s *Switch) CircuitLookup() CircuitLookup {
3✔
2526
        return s.circuits
3✔
2527
}
3✔
2528

2529
// commitCircuits persistently adds a circuit to the switch's circuit map.
2530
func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
2531
        *CircuitFwdActions, error) {
17✔
2532

17✔
2533
        return s.circuits.CommitCircuits(circuits...)
17✔
2534
}
17✔
2535

2536
// FlushForwardingEvents flushes out the set of pending forwarding events to
2537
// the persistent log. This will be used by the switch to periodically flush
2538
// out the set of forwarding events to disk. External callers can also use this
2539
// method to ensure all data is flushed to dis before querying the log.
2540
func (s *Switch) FlushForwardingEvents() error {
212✔
2541
        // First, we'll obtain a copy of the current set of pending forwarding
212✔
2542
        // events.
212✔
2543
        s.fwdEventMtx.Lock()
212✔
2544

212✔
2545
        // If we won't have any forwarding events, then we can exit early.
212✔
2546
        if len(s.pendingFwdingEvents) == 0 {
407✔
2547
                s.fwdEventMtx.Unlock()
195✔
2548
                return nil
195✔
2549
        }
195✔
2550

2551
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
20✔
2552
        copy(events[:], s.pendingFwdingEvents[:])
20✔
2553

20✔
2554
        // With the copy obtained, we can now clear out the header pointer of
20✔
2555
        // the current slice. This way, we can re-use the underlying storage
20✔
2556
        // allocated for the slice.
20✔
2557
        s.pendingFwdingEvents = s.pendingFwdingEvents[:0]
20✔
2558
        s.fwdEventMtx.Unlock()
20✔
2559

20✔
2560
        // Finally, we'll write out the copied events to the persistent
20✔
2561
        // forwarding log.
20✔
2562
        return s.cfg.FwdingLog.AddForwardingEvents(events)
20✔
2563
}
2564

2565
// BestHeight returns the best height known to the switch.
2566
func (s *Switch) BestHeight() uint32 {
450✔
2567
        return atomic.LoadUint32(&s.bestHeight)
450✔
2568
}
450✔
2569

2570
// dustExceedsFeeThreshold takes in a ChannelLink, HTLC amount, and a boolean
2571
// to determine whether the default fee threshold has been exceeded. This
2572
// heuristic takes into account the trimmed-to-dust mechanism. The sum of the
2573
// commitment's dust with the mailbox's dust with the amount is checked against
2574
// the fee exposure threshold. If incoming is true, then the amount is not
2575
// included in the sum as it was already included in the commitment's dust. A
2576
// boolean is returned telling the caller whether the HTLC should be failed
2577
// back.
2578
func (s *Switch) dustExceedsFeeThreshold(link ChannelLink,
2579
        amount lnwire.MilliSatoshi, incoming bool) bool {
535✔
2580

535✔
2581
        // Retrieve the link's current commitment feerate and dustClosure.
535✔
2582
        feeRate := link.getFeeRate()
535✔
2583
        isDust := link.getDustClosure()
535✔
2584

535✔
2585
        // Evaluate if the HTLC is dust on either sides' commitment.
535✔
2586
        isLocalDust := isDust(
535✔
2587
                feeRate, incoming, lntypes.Local, amount.ToSatoshis(),
535✔
2588
        )
535✔
2589
        isRemoteDust := isDust(
535✔
2590
                feeRate, incoming, lntypes.Remote, amount.ToSatoshis(),
535✔
2591
        )
535✔
2592

535✔
2593
        if !(isLocalDust || isRemoteDust) {
670✔
2594
                // If the HTLC is not dust on either commitment, it's fine to
135✔
2595
                // forward.
135✔
2596
                return false
135✔
2597
        }
135✔
2598

2599
        // Fetch the dust sums currently in the mailbox for this link.
2600
        cid := link.ChanID()
403✔
2601
        sid := link.ShortChanID()
403✔
2602
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
403✔
2603
        localMailDust, remoteMailDust := mailbox.DustPackets()
403✔
2604

403✔
2605
        // If the htlc is dust on the local commitment, we'll obtain the dust
403✔
2606
        // sum for it.
403✔
2607
        if isLocalDust {
806✔
2608
                localSum := link.getDustSum(
403✔
2609
                        lntypes.Local, fn.None[chainfee.SatPerKWeight](),
403✔
2610
                )
403✔
2611
                localSum += localMailDust
403✔
2612

403✔
2613
                // Optionally include the HTLC amount only for outgoing
403✔
2614
                // HTLCs.
403✔
2615
                if !incoming {
766✔
2616
                        localSum += amount
363✔
2617
                }
363✔
2618

2619
                // Finally check against the defined fee threshold.
2620
                if localSum > s.cfg.MaxFeeExposure {
405✔
2621
                        return true
2✔
2622
                }
2✔
2623
        }
2624

2625
        // Also check if the htlc is dust on the remote commitment, if we've
2626
        // reached this point.
2627
        if isRemoteDust {
802✔
2628
                remoteSum := link.getDustSum(
401✔
2629
                        lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
401✔
2630
                )
401✔
2631
                remoteSum += remoteMailDust
401✔
2632

401✔
2633
                // Optionally include the HTLC amount only for outgoing
401✔
2634
                // HTLCs.
401✔
2635
                if !incoming {
762✔
2636
                        remoteSum += amount
361✔
2637
                }
361✔
2638

2639
                // Finally check against the defined fee threshold.
2640
                if remoteSum > s.cfg.MaxFeeExposure {
401✔
2641
                        return true
×
2642
                }
×
2643
        }
2644

2645
        // If we reached this point, this HTLC is fine to forward.
2646
        return false
401✔
2647
}
2648

2649
// failMailboxUpdate is passed to the mailbox orchestrator which in turn passes
2650
// it to individual mailboxes. It allows the mailboxes to construct a
2651
// FailureMessage when failing back HTLC's due to expiry and may include an
2652
// alias in the ShortChannelID field. The outgoingScid is the SCID originally
2653
// used in the onion. The mailboxScid is the SCID that the mailbox and link
2654
// use. The mailboxScid is only used in the non-alias case, so it is always
2655
// the confirmed SCID.
2656
func (s *Switch) failMailboxUpdate(outgoingScid,
2657
        mailboxScid lnwire.ShortChannelID) lnwire.FailureMessage {
12✔
2658

12✔
2659
        // Try to use the failAliasUpdate function in case this is a channel
12✔
2660
        // that uses aliases. If it returns nil, we'll fallback to the original
12✔
2661
        // pre-alias behavior.
12✔
2662
        update := s.failAliasUpdate(outgoingScid, false)
12✔
2663
        if update == nil {
18✔
2664
                // Execute the fallback behavior.
6✔
2665
                var err error
6✔
2666
                update, err = s.cfg.FetchLastChannelUpdate(mailboxScid)
6✔
2667
                if err != nil {
6✔
2668
                        return &lnwire.FailTemporaryNodeFailure{}
×
2669
                }
×
2670
        }
2671

2672
        return lnwire.NewTemporaryChannelFailure(update)
12✔
2673
}
2674

2675
// failAliasUpdate prepares a ChannelUpdate for a failed incoming or outgoing
2676
// HTLC on a channel where the option-scid-alias feature bit was negotiated. If
2677
// the associated channel is not one of these, this function will return nil
2678
// and the caller is expected to handle this properly. In this case, a return
2679
// to the original non-alias behavior is expected.
2680
func (s *Switch) failAliasUpdate(scid lnwire.ShortChannelID,
2681
        incoming bool) *lnwire.ChannelUpdate1 {
37✔
2682

37✔
2683
        // This function does not defer the unlocking because of the database
37✔
2684
        // lookups for ChannelUpdate.
37✔
2685
        s.indexMtx.RLock()
37✔
2686

37✔
2687
        if s.cfg.IsAlias(scid) {
51✔
2688
                // The alias SCID was used. In the incoming case this means
14✔
2689
                // the channel is zero-conf as the link sets the scid. In the
14✔
2690
                // outgoing case, the sender set the scid to use and may be
14✔
2691
                // either the alias or the confirmed one, if it exists.
14✔
2692
                realScid, ok := s.aliasToReal[scid]
14✔
2693
                if !ok {
14✔
2694
                        // The real, confirmed SCID does not exist yet. Find
×
2695
                        // the "base" SCID that the link uses via the
×
2696
                        // baseIndex. If we can't find it, return nil. This
×
2697
                        // means the channel is zero-conf.
×
2698
                        baseScid, ok := s.baseIndex[scid]
×
2699
                        s.indexMtx.RUnlock()
×
2700
                        if !ok {
×
2701
                                return nil
×
2702
                        }
×
2703

2704
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2705
                        if err != nil {
×
2706
                                return nil
×
2707
                        }
×
2708

2709
                        // Replace the baseScid with the passed-in alias.
2710
                        update.ShortChannelID = scid
×
2711
                        sig, err := s.cfg.SignAliasUpdate(update)
×
2712
                        if err != nil {
×
2713
                                return nil
×
2714
                        }
×
2715

2716
                        update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2717
                        if err != nil {
×
2718
                                return nil
×
2719
                        }
×
2720

2721
                        return update
×
2722
                }
2723

2724
                s.indexMtx.RUnlock()
14✔
2725

14✔
2726
                // Fetch the SCID via the confirmed SCID and replace it with
14✔
2727
                // the alias.
14✔
2728
                update, err := s.cfg.FetchLastChannelUpdate(realScid)
14✔
2729
                if err != nil {
17✔
2730
                        return nil
3✔
2731
                }
3✔
2732

2733
                // In the incoming case, we want to ensure that we don't leak
2734
                // the UTXO in case the channel is private. In the outgoing
2735
                // case, since the alias was used, we do the same thing.
2736
                update.ShortChannelID = scid
14✔
2737
                sig, err := s.cfg.SignAliasUpdate(update)
14✔
2738
                if err != nil {
14✔
2739
                        return nil
×
2740
                }
×
2741

2742
                update.Signature, err = lnwire.NewSigFromSignature(sig)
14✔
2743
                if err != nil {
14✔
2744
                        return nil
×
2745
                }
×
2746

2747
                return update
14✔
2748
        }
2749

2750
        // If the confirmed SCID is not in baseIndex, this is not an
2751
        // option-scid-alias or zero-conf channel.
2752
        baseScid, ok := s.baseIndex[scid]
26✔
2753
        if !ok {
47✔
2754
                s.indexMtx.RUnlock()
21✔
2755
                return nil
21✔
2756
        }
21✔
2757

2758
        // Fetch the link so we can get an alias to use in the ShortChannelID
2759
        // of the ChannelUpdate.
2760
        link, ok := s.forwardingIndex[baseScid]
5✔
2761
        s.indexMtx.RUnlock()
5✔
2762
        if !ok {
5✔
2763
                // This should never happen, but if it does for some reason,
×
2764
                // fallback to the old behavior.
×
2765
                return nil
×
2766
        }
×
2767

2768
        aliases := link.getAliases()
5✔
2769
        if len(aliases) == 0 {
5✔
2770
                // This should never happen, but if it does, fallback.
×
2771
                return nil
×
2772
        }
×
2773

2774
        // Fetch the ChannelUpdate via the real, confirmed SCID.
2775
        update, err := s.cfg.FetchLastChannelUpdate(scid)
5✔
2776
        if err != nil {
5✔
2777
                return nil
×
2778
        }
×
2779

2780
        // The incoming case will replace the ShortChannelID in the retrieved
2781
        // ChannelUpdate with the alias to ensure no privacy leak occurs. This
2782
        // would happen if a private non-zero-conf option-scid-alias
2783
        // feature-bit channel leaked its UTXO here rather than supplying an
2784
        // alias. In the outgoing case, the confirmed SCID was actually used
2785
        // for forwarding in the onion, so no replacement is necessary as the
2786
        // sender knows the scid.
2787
        if incoming {
7✔
2788
                // We will replace and sign the update with the first alias.
2✔
2789
                // Since this happens on the incoming side, it's not actually
2✔
2790
                // possible to know what the sender used in the onion.
2✔
2791
                update.ShortChannelID = aliases[0]
2✔
2792
                sig, err := s.cfg.SignAliasUpdate(update)
2✔
2793
                if err != nil {
2✔
2794
                        return nil
×
2795
                }
×
2796

2797
                update.Signature, err = lnwire.NewSigFromSignature(sig)
2✔
2798
                if err != nil {
2✔
2799
                        return nil
×
2800
                }
×
2801
        }
2802

2803
        return update
5✔
2804
}
2805

2806
// AddAliasForLink instructs the Switch to update its in-memory maps to reflect
2807
// that a link has a new alias.
2808
func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
2809
        alias lnwire.ShortChannelID) error {
×
2810

×
2811
        // Fetch the link so that we can update the underlying channel's set of
×
2812
        // aliases.
×
2813
        s.indexMtx.RLock()
×
2814
        link, err := s.getLink(chanID)
×
2815
        s.indexMtx.RUnlock()
×
2816
        if err != nil {
×
2817
                return err
×
2818
        }
×
2819

2820
        // If the link is a channel where the option-scid-alias feature bit was
2821
        // not negotiated, we'll return an error.
2822
        if !link.negotiatedAliasFeature() {
×
2823
                return fmt.Errorf("attempted to update non-alias channel")
×
2824
        }
×
2825

2826
        linkScid := link.ShortChanID()
×
2827

×
2828
        // We'll update the maps so the Switch includes this alias in its
×
2829
        // forwarding decisions.
×
2830
        if link.isZeroConf() {
×
2831
                if link.zeroConfConfirmed() {
×
2832
                        // If the channel has confirmed on-chain, we'll
×
2833
                        // add this alias to the aliasToReal map.
×
2834
                        confirmedScid := link.confirmedScid()
×
2835

×
2836
                        s.aliasToReal[alias] = confirmedScid
×
2837
                }
×
2838

2839
                // Add this alias to the baseIndex mapping.
2840
                s.baseIndex[alias] = linkScid
×
2841
        } else if link.negotiatedAliasFeature() {
×
2842
                // The channel is confirmed, so we'll populate the aliasToReal
×
2843
                // and baseIndex maps.
×
2844
                s.aliasToReal[alias] = linkScid
×
2845
                s.baseIndex[alias] = linkScid
×
2846
        }
×
2847

2848
        return nil
×
2849
}
2850

2851
// handlePacketAdd handles forwarding an Add packet.
2852
func (s *Switch) handlePacketAdd(packet *htlcPacket,
2853
        htlc *lnwire.UpdateAddHTLC) error {
85✔
2854

85✔
2855
        // Check if the node is set to reject all onward HTLCs and also make
85✔
2856
        // sure that HTLC is not from the source node.
85✔
2857
        if s.cfg.RejectHTLC {
89✔
2858
                failure := NewDetailedLinkError(
4✔
2859
                        &lnwire.FailChannelDisabled{},
4✔
2860
                        OutgoingFailureForwardsDisabled,
4✔
2861
                )
4✔
2862

4✔
2863
                return s.failAddPacket(packet, failure)
4✔
2864
        }
4✔
2865

2866
        // Before we attempt to find a non-strict forwarding path for this
2867
        // htlc, check whether the htlc is being routed over the same incoming
2868
        // and outgoing channel. If our node does not allow forwards of this
2869
        // nature, we fail the htlc early. This check is in place to disallow
2870
        // inefficiently routed htlcs from locking up our balance. With
2871
        // channels where the option-scid-alias feature was negotiated, we also
2872
        // have to be sure that the IDs aren't the same since one or both could
2873
        // be an alias.
2874
        linkErr := s.checkCircularForward(
84✔
2875
                packet.incomingChanID, packet.outgoingChanID,
84✔
2876
                s.cfg.AllowCircularRoute, htlc.PaymentHash,
84✔
2877
        )
84✔
2878
        if linkErr != nil {
85✔
2879
                return s.failAddPacket(packet, linkErr)
1✔
2880
        }
1✔
2881

2882
        s.indexMtx.RLock()
83✔
2883
        targetLink, err := s.getLinkByMapping(packet)
83✔
2884
        if err != nil {
90✔
2885
                s.indexMtx.RUnlock()
7✔
2886

7✔
2887
                log.Debugf("unable to find link with "+
7✔
2888
                        "destination %v", packet.outgoingChanID)
7✔
2889

7✔
2890
                // If packet was forwarded from another channel link than we
7✔
2891
                // should notify this link that some error occurred.
7✔
2892
                linkError := NewLinkError(
7✔
2893
                        &lnwire.FailUnknownNextPeer{},
7✔
2894
                )
7✔
2895

7✔
2896
                return s.failAddPacket(packet, linkError)
7✔
2897
        }
7✔
2898
        targetPeerKey := targetLink.PeerPubKey()
79✔
2899
        interfaceLinks, _ := s.getLinks(targetPeerKey)
79✔
2900
        s.indexMtx.RUnlock()
79✔
2901

79✔
2902
        // We'll keep track of any HTLC failures during the link selection
79✔
2903
        // process. This way we can return the error for precise link that the
79✔
2904
        // sender selected, while optimistically trying all links to utilize
79✔
2905
        // our available bandwidth.
79✔
2906
        linkErrs := make(map[lnwire.ShortChannelID]*LinkError)
79✔
2907

79✔
2908
        // Find all destination channel links with appropriate bandwidth.
79✔
2909
        var destinations []ChannelLink
79✔
2910
        for _, link := range interfaceLinks {
162✔
2911
                var failure *LinkError
83✔
2912

83✔
2913
                // We'll skip any links that aren't yet eligible for
83✔
2914
                // forwarding.
83✔
2915
                if !link.EligibleToForward() {
87✔
2916
                        failure = NewDetailedLinkError(
4✔
2917
                                &lnwire.FailUnknownNextPeer{},
4✔
2918
                                OutgoingFailureLinkNotEligible,
4✔
2919
                        )
4✔
2920
                } else {
83✔
2921
                        // We'll ensure that the HTLC satisfies the current
79✔
2922
                        // forwarding conditions of this target link.
79✔
2923
                        currentHeight := atomic.LoadUint32(&s.bestHeight)
79✔
2924
                        failure = link.CheckHtlcForward(
79✔
2925
                                htlc.PaymentHash, packet.incomingAmount,
79✔
2926
                                packet.amount, packet.incomingTimeout,
79✔
2927
                                packet.outgoingTimeout, packet.inboundFee,
79✔
2928
                                currentHeight, packet.originalOutgoingChanID,
79✔
2929
                                htlc.CustomRecords,
79✔
2930
                        )
79✔
2931
                }
79✔
2932

2933
                // If this link can forward the htlc, add it to the set of
2934
                // destinations.
2935
                if failure == nil {
146✔
2936
                        destinations = append(destinations, link)
63✔
2937
                        continue
63✔
2938
                }
2939

2940
                linkErrs[link.ShortChanID()] = failure
23✔
2941
        }
2942

2943
        // If we had a forwarding failure due to the HTLC not satisfying the
2944
        // current policy, then we'll send back an error, but ensure we send
2945
        // back the error sourced at the *target* link.
2946
        if len(destinations) == 0 {
98✔
2947
                // At this point, some or all of the links rejected the HTLC so
19✔
2948
                // we couldn't forward it. So we'll try to look up the error
19✔
2949
                // that came from the source.
19✔
2950
                linkErr, ok := linkErrs[packet.outgoingChanID]
19✔
2951
                if !ok {
19✔
2952
                        // If we can't find the error of the source, then we'll
×
2953
                        // return an unknown next peer, though this should
×
2954
                        // never happen.
×
2955
                        linkErr = NewLinkError(
×
2956
                                &lnwire.FailUnknownNextPeer{},
×
2957
                        )
×
2958
                        log.Warnf("unable to find err source for "+
×
2959
                                "outgoing_link=%v, errors=%v",
×
2960
                                packet.outgoingChanID,
×
2961
                                lnutils.SpewLogClosure(linkErrs))
×
2962
                }
×
2963

2964
                log.Tracef("incoming HTLC(%x) violated "+
19✔
2965
                        "target outgoing link (id=%v) policy: %v",
19✔
2966
                        htlc.PaymentHash[:], packet.outgoingChanID,
19✔
2967
                        linkErr)
19✔
2968

19✔
2969
                return s.failAddPacket(packet, linkErr)
19✔
2970
        }
2971

2972
        // Choose a random link out of the set of links that can forward this
2973
        // htlc. The reason for randomization is to evenly distribute the htlc
2974
        // load without making assumptions about what the best channel is.
2975
        //nolint:gosec
2976
        destination := destinations[rand.Intn(len(destinations))]
63✔
2977

63✔
2978
        // Retrieve the incoming link by its ShortChannelID. Note that the
63✔
2979
        // incomingChanID is never set to hop.Source here.
63✔
2980
        s.indexMtx.RLock()
63✔
2981
        incomingLink, err := s.getLinkByShortID(packet.incomingChanID)
63✔
2982
        s.indexMtx.RUnlock()
63✔
2983
        if err != nil {
63✔
2984
                // If we couldn't find the incoming link, we can't evaluate the
×
2985
                // incoming's exposure to dust, so we just fail the HTLC back.
×
2986
                linkErr := NewLinkError(
×
2987
                        &lnwire.FailTemporaryChannelFailure{},
×
2988
                )
×
2989

×
2990
                return s.failAddPacket(packet, linkErr)
×
2991
        }
×
2992

2993
        // Evaluate whether this HTLC would increase our fee exposure over the
2994
        // threshold on the incoming link. If it does, fail it backwards.
2995
        if s.dustExceedsFeeThreshold(
63✔
2996
                incomingLink, packet.incomingAmount, true,
63✔
2997
        ) {
63✔
2998
                // The incoming dust exceeds the threshold, so we fail the add
×
2999
                // back.
×
3000
                linkErr := NewLinkError(
×
3001
                        &lnwire.FailTemporaryChannelFailure{},
×
3002
                )
×
3003

×
3004
                return s.failAddPacket(packet, linkErr)
×
3005
        }
×
3006

3007
        // Also evaluate whether this HTLC would increase our fee exposure over
3008
        // the threshold on the destination link. If it does, fail it back.
3009
        if s.dustExceedsFeeThreshold(
63✔
3010
                destination, packet.amount, false,
63✔
3011
        ) {
64✔
3012
                // The outgoing dust exceeds the threshold, so we fail the add
1✔
3013
                // back.
1✔
3014
                linkErr := NewLinkError(
1✔
3015
                        &lnwire.FailTemporaryChannelFailure{},
1✔
3016
                )
1✔
3017

1✔
3018
                return s.failAddPacket(packet, linkErr)
1✔
3019
        }
1✔
3020

3021
        // Send the packet to the destination channel link which manages the
3022
        // channel.
3023
        packet.outgoingChanID = destination.ShortChanID()
62✔
3024

62✔
3025
        return destination.handleSwitchPacket(packet)
62✔
3026
}
3027

3028
// handlePacketSettle handles forwarding a settle packet.
3029
func (s *Switch) handlePacketSettle(packet *htlcPacket) error {
403✔
3030
        // If the source of this packet has not been set, use the circuit map
403✔
3031
        // to lookup the origin.
403✔
3032
        circuit, err := s.closeCircuit(packet)
403✔
3033

403✔
3034
        // If the circuit is in the process of closing, we will return a nil as
403✔
3035
        // there's another packet handling undergoing.
403✔
3036
        if errors.Is(err, ErrCircuitClosing) {
406✔
3037
                log.Debugf("Circuit is closing for packet=%v", packet)
3✔
3038
                return nil
3✔
3039
        }
3✔
3040

3041
        // Exit early if there's another error.
3042
        if err != nil {
403✔
3043
                return err
×
3044
        }
×
3045

3046
        // closeCircuit returns a nil circuit when a settle packet returns an
3047
        // ErrUnknownCircuit error upon the inner call to CloseCircuit.
3048
        //
3049
        // NOTE: We can only get a nil circuit when it has already been deleted
3050
        // and when `UpdateFulfillHTLC` is received. After which `RevokeAndAck`
3051
        // is received, which invokes `processRemoteSettleFails` in its link.
3052
        if circuit == nil {
597✔
3053
                log.Debugf("Circuit already closed for packet=%v", packet)
194✔
3054
                return nil
194✔
3055
        }
194✔
3056

3057
        localHTLC := packet.incomingChanID == hop.Source
212✔
3058

212✔
3059
        // If this is a locally initiated HTLC, we need to handle the packet by
212✔
3060
        // storing the network result.
212✔
3061
        //
212✔
3062
        // A blank IncomingChanID in a circuit indicates that it is a pending
212✔
3063
        // user-initiated payment.
212✔
3064
        //
212✔
3065
        // NOTE: `closeCircuit` modifies the state of `packet`.
212✔
3066
        if localHTLC {
395✔
3067
                // TODO(yy): remove the goroutine and send back the error here.
183✔
3068
                s.wg.Add(1)
183✔
3069
                go s.handleLocalResponse(packet)
183✔
3070

183✔
3071
                // If this is a locally initiated HTLC, there's no need to
183✔
3072
                // forward it so we exit.
183✔
3073
                return nil
183✔
3074
        }
183✔
3075

3076
        // If this is an HTLC settle, and it wasn't from a locally initiated
3077
        // HTLC, then we'll log a forwarding event so we can flush it to disk
3078
        // later.
3079
        if circuit.Outgoing != nil {
64✔
3080
                log.Infof("Forwarded HTLC(%x) of %v (fee: %v) "+
32✔
3081
                        "from IncomingChanID(%v) to OutgoingChanID(%v)",
32✔
3082
                        circuit.PaymentHash[:], circuit.OutgoingAmount,
32✔
3083
                        circuit.IncomingAmount-circuit.OutgoingAmount,
32✔
3084
                        circuit.Incoming.ChanID, circuit.Outgoing.ChanID)
32✔
3085

32✔
3086
                s.fwdEventMtx.Lock()
32✔
3087
                s.pendingFwdingEvents = append(
32✔
3088
                        s.pendingFwdingEvents,
32✔
3089
                        channeldb.ForwardingEvent{
32✔
3090
                                Timestamp:      time.Now(),
32✔
3091
                                IncomingChanID: circuit.Incoming.ChanID,
32✔
3092
                                OutgoingChanID: circuit.Outgoing.ChanID,
32✔
3093
                                AmtIn:          circuit.IncomingAmount,
32✔
3094
                                AmtOut:         circuit.OutgoingAmount,
32✔
3095
                                IncomingHtlcID: fn.Some(
32✔
3096
                                        circuit.Incoming.HtlcID,
32✔
3097
                                ),
32✔
3098
                                OutgoingHtlcID: fn.Some(
32✔
3099
                                        circuit.Outgoing.HtlcID,
32✔
3100
                                ),
32✔
3101
                        },
32✔
3102
                )
32✔
3103
                s.fwdEventMtx.Unlock()
32✔
3104
        }
32✔
3105

3106
        // Deliver this packet.
3107
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
32✔
3108
}
3109

3110
// handlePacketFail handles forwarding a fail packet.
3111
func (s *Switch) handlePacketFail(packet *htlcPacket,
3112
        htlc *lnwire.UpdateFailHTLC) error {
141✔
3113

141✔
3114
        // If the source of this packet has not been set, use the circuit map
141✔
3115
        // to lookup the origin.
141✔
3116
        circuit, err := s.closeCircuit(packet)
141✔
3117
        if err != nil {
141✔
3118
                return err
×
3119
        }
×
3120

3121
        // If this is a locally initiated HTLC, we need to handle the packet by
3122
        // storing the network result.
3123
        //
3124
        // A blank IncomingChanID in a circuit indicates that it is a pending
3125
        // user-initiated payment.
3126
        //
3127
        // NOTE: `closeCircuit` modifies the state of `packet`.
3128
        if packet.incomingChanID == hop.Source {
268✔
3129
                // TODO(yy): remove the goroutine and send back the error here.
127✔
3130
                s.wg.Add(1)
127✔
3131
                go s.handleLocalResponse(packet)
127✔
3132

127✔
3133
                // If this is a locally initiated HTLC, there's no need to
127✔
3134
                // forward it so we exit.
127✔
3135
                return nil
127✔
3136
        }
127✔
3137

3138
        // Exit early if this hasSource is true. This flag is only set via
3139
        // mailbox's `FailAdd`. This method has two callsites,
3140
        // - the packet has timed out after `MailboxDeliveryTimeout`, defaults
3141
        //   to 1 min.
3142
        // - the HTLC fails the validation in `channel.AddHTLC`.
3143
        // In either case, the `Reason` field is populated. Thus there's no
3144
        // need to proceed and extract the failure reason below.
3145
        if packet.hasSource {
24✔
3146
                // Deliver this packet.
7✔
3147
                return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
7✔
3148
        }
7✔
3149

3150
        // HTLC resolutions and messages restored from disk don't have the
3151
        // obfuscator set from the original htlc add packet - set it here for
3152
        // use in blinded errors.
3153
        packet.obfuscator = circuit.ErrorEncrypter
10✔
3154

10✔
3155
        switch {
10✔
3156
        // No message to encrypt, locally sourced payment.
3157
        case circuit.ErrorEncrypter == nil:
×
3158
                // TODO(yy) further check this case as we shouldn't end up here
3159
                // as `isLocal` is already false.
3160

3161
        // If this is a resolution message, then we'll need to encrypt it as
3162
        // it's actually internally sourced.
3163
        case packet.isResolution:
3✔
3164
                var err error
3✔
3165
                // TODO(roasbeef): don't need to pass actually?
3✔
3166
                failure := &lnwire.FailPermanentChannelFailure{}
3✔
3167
                htlc.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
3✔
3168
                        failure,
3✔
3169
                )
3✔
3170
                if err != nil {
3✔
3171
                        err = fmt.Errorf("unable to obfuscate error: %w", err)
×
3172
                        log.Error(err)
×
3173
                }
×
3174

3175
        // Alternatively, if the remote party sends us an
3176
        // UpdateFailMalformedHTLC, then we'll need to convert this into a
3177
        // proper well formatted onion error as there's no HMAC currently.
3178
        case packet.convertedError:
5✔
3179
                log.Infof("Converting malformed HTLC error for circuit for "+
5✔
3180
                        "Circuit(%x: (%s, %d) <-> (%s, %d))",
5✔
3181
                        packet.circuit.PaymentHash,
5✔
3182
                        packet.incomingChanID, packet.incomingHTLCID,
5✔
3183
                        packet.outgoingChanID, packet.outgoingHTLCID)
5✔
3184

5✔
3185
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
5✔
3186
                        htlc.Reason,
5✔
3187
                )
5✔
3188

3189
        default:
8✔
3190
                // Otherwise, it's a forwarded error, so we'll perform a
8✔
3191
                // wrapper encryption as normal.
8✔
3192
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
8✔
3193
                        htlc.Reason,
8✔
3194
                )
8✔
3195
        }
3196

3197
        // Deliver this packet.
3198
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
10✔
3199
}
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