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

lightningnetwork / lnd / 14721313522

29 Apr 2025 01:25AM UTC coverage: 58.598% (+0.006%) from 58.592%
14721313522

Pull #9489

github

web-flow
Merge 290053529 into b34afa33f
Pull Request #9489: multi: add BuildOnion, SendOnion, and TrackOnion RPCs

360 of 553 new or added lines in 10 files covered. (65.1%)

83 existing lines in 10 files now uncovered.

97747 of 166809 relevant lines covered (58.6%)

1.82 hits per line

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

74.94
/htlcswitch/switch.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
        errChan chan error
412
}
413

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

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

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

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

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

451
        return false, nil
3✔
452
}
453

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

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

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

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

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

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

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

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

533
        return resultChan, nil
3✔
534
}
535

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

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

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

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

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

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

×
604
                return errFeeExposureExceeded
×
605
        }
×
606

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

823
        return nil
3✔
824
}
825

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1010
// extractResult uses the given deobfuscator to extract the payment result from
1011
// the given network message. If the deobfuscator is not present, then we'll
1012
// return the onion-encrypted blob that details why the HTLC was failed. This
1013
// blob is only fully decryptable by the entity which built the onion packet.
1014
func (s *Switch) extractResult(deobfuscator ErrorDecrypter, n *networkResult,
1015
        attemptID uint64, paymentHash lntypes.Hash) (*PaymentResult, error) {
3✔
1016

3✔
1017
        switch htlc := n.msg.(type) {
3✔
1018

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

1026
        // We've received a fail update which means we can finalize the
1027
        // user payment and return fail response.
1028
        case *lnwire.UpdateFailHTLC:
3✔
1029
                if deobfuscator == nil {
6✔
1030
                        return &PaymentResult{
3✔
1031
                                EncryptedError: htlc.Reason,
3✔
1032
                        }, nil
3✔
1033
                }
3✔
1034

1035
                // TODO(yy): construct deobfuscator here to avoid creating it
1036
                // in paymentLifecycle even for settled HTLCs.
1037
                paymentErr := s.parseFailedPayment(
3✔
1038
                        deobfuscator, attemptID, paymentHash, n.unencrypted,
3✔
1039
                        n.isResolution, htlc,
3✔
1040
                )
3✔
1041

3✔
1042
                return &PaymentResult{
3✔
1043
                        Error: paymentErr,
3✔
1044
                }, nil
3✔
1045

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

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

3✔
1063
        switch {
3✔
1064

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

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

×
1086
                        return linkError
×
1087
                }
×
1088

1089
                // If we successfully decoded the failure reason, return it.
1090
                return NewLinkError(failureMsg)
3✔
1091

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

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

3✔
1106
                return linkError
3✔
1107

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

×
1119
                        return ErrUnreadableFailureMessage
×
1120
                }
×
1121

1122
                return failure
3✔
1123
        }
1124
}
1125

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

1137
        case *lnwire.UpdateFulfillHTLC:
3✔
1138
                return s.handlePacketSettle(packet)
3✔
1139

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

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

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

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

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

1173
                // Otherwise, we'll return a temporary channel failure.
1174
                return NewDetailedLinkError(
×
1175
                        lnwire.NewTemporaryChannelFailure(nil),
×
1176
                        OutgoingFailureCircularRoute,
×
1177
                )
×
1178
        }
1179

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

1193
        outgoingBaseScid, ok := s.baseIndex[outgoing]
3✔
1194
        if !ok {
6✔
1195
                // This channel does not use baseIndex, bail out.
3✔
1196
                s.indexMtx.RUnlock()
3✔
1197
                return nil
3✔
1198
        }
3✔
1199
        s.indexMtx.RUnlock()
3✔
1200

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

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

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

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

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

1246
        log.Error(failure.Error())
3✔
1247

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

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

1279
        return failure
3✔
1280
}
1281

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

1294
                // Circuit successfully closed.
1295
                case nil:
3✔
1296
                        return circuit, nil
3✔
1297

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

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

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

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

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

3✔
1329
                pktType := "SETTLE"
3✔
1330
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
6✔
1331
                        pktType = "FAIL"
3✔
1332
                }
3✔
1333

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

3✔
1339
                return circuit, nil
3✔
1340

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

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

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

×
1367
                        return nil, err
×
1368
                }
×
1369

1370
                return nil, nil
3✔
1371

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

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

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

1401
        var paymentHash lntypes.Hash
3✔
1402

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

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

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

×
1420
                return err
×
1421
        }
×
1422

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

3✔
1427
        return nil
3✔
1428
}
1429

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

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

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

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

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

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

3✔
1479
        defer func() {
6✔
1480
                s.blockEpochStream.Cancel()
3✔
1481

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

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

3✔
1515
                                l.Stop()
3✔
1516
                        }(link)
3✔
1517
                }
1518
                wg.Wait()
3✔
1519

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

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

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

3✔
1542
        defer s.cfg.AckEventTicker.Stop()
3✔
1543

3✔
1544
out:
3✔
1545
        for {
6✔
1546

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

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

1559
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
3✔
1560

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

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

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

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

3✔
1582
                        go s.cfg.LocalChannelClose(peerPub[:], req)
3✔
1583

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

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

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

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

1629
                        log.Debugf("Received outside contract resolution, "+
3✔
1630
                                "mapping to: %v", spew.Sdump(pkt))
3✔
1631

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

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

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

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

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

3✔
1671
                        var (
3✔
1672
                                newNumUpdates uint64
3✔
1673
                                newSatSent    btcutil.Amount
3✔
1674
                                newSatRecv    btcutil.Amount
3✔
1675
                        )
3✔
1676

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

3✔
1690
                        var (
3✔
1691
                                diffNumUpdates uint64
3✔
1692
                                diffSatSent    btcutil.Amount
3✔
1693
                                diffSatRecv    btcutil.Amount
3✔
1694
                        )
3✔
1695

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

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

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

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

3✔
1734
                        totalNumUpdates += diffNumUpdates
3✔
1735
                        totalSatSent += diffSatSent
3✔
1736
                        totalSatRecv += diffSatRecv
3✔
1737

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

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

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

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

1762
                case <-s.quit:
3✔
1763
                        return
3✔
1764
                }
1765
        }
1766
}
1767

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

1775
        log.Infof("HTLC Switch starting")
3✔
1776

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

3✔
1783
        s.wg.Add(1)
3✔
1784
        go s.htlcForwarder()
3✔
1785

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

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

1799
        return nil
3✔
1800
}
1801

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

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

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

1829
                        continue
3✔
1830
                }
1831

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

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

1850
                switchPackets = append(switchPackets, resPkt)
3✔
1851
        }
1852

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

1860
        return nil
3✔
1861
}
1862

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

1874
        for _, openChannel := range openChannels {
6✔
1875
                shortChanID := openChannel.ShortChanID()
3✔
1876

3✔
1877
                // Locally-initiated payments never need reforwarding.
3✔
1878
                if shortChanID == hop.Source {
6✔
1879
                        continue
3✔
1880
                }
1881

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

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

1901
                s.reforwardSettleFails(fwdPkgs)
3✔
1902
        }
1903

1904
        return nil
3✔
1905
}
1906

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

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

1924
        return fwdPkgs, nil
3✔
1925
}
1926

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

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

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

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

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

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

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

2011
        log.Info("HTLC Switch shutting down...")
3✔
2012
        defer log.Debug("HTLC Switch shutdown complete")
3✔
2013

3✔
2014
        close(s.quit)
3✔
2015

3✔
2016
        s.wg.Wait()
3✔
2017

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

3✔
2023
        return nil
3✔
2024
}
2025

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

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

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

3✔
2041
        chanID := link.ChanID()
3✔
2042

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

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

3✔
2057
        // Attach the Switch's failAliasUpdate function to the link.
3✔
2058
        link.attachFailAliasUpdate(s.failAliasUpdate)
3✔
2059

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

2067
        if shortChanID == hop.Source {
6✔
2068
                log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
3✔
2069
                        chanID, shortChanID)
3✔
2070

3✔
2071
                s.pendingLinkIndex[chanID] = link
3✔
2072
        } else {
6✔
2073
                log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
3✔
2074
                        chanID, shortChanID)
3✔
2075

3✔
2076
                s.addLiveLink(link)
3✔
2077
                s.mailOrchestrator.BindLiveShortChanID(
3✔
2078
                        mailbox, chanID, shortChanID,
3✔
2079
                )
3✔
2080
        }
3✔
2081

2082
        return nil
3✔
2083
}
2084

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

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

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

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

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

3✔
2114
        s.updateLinkAliases(link)
3✔
2115
}
3✔
2116

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

3✔
2125
        aliases := link.getAliases()
3✔
2126
        if link.isZeroConf() {
6✔
2127
                if link.zeroConfConfirmed() {
6✔
2128
                        // Since the zero-conf channel has confirmed, we can
3✔
2129
                        // populate the aliasToReal mapping.
3✔
2130
                        confirmedScid := link.confirmedScid()
3✔
2131

3✔
2132
                        for _, alias := range aliases {
6✔
2133
                                s.aliasToReal[alias] = confirmedScid
3✔
2134
                        }
3✔
2135

2136
                        // Add the confirmed SCID as a key in the baseIndex.
2137
                        s.baseIndex[confirmedScid] = linkScid
3✔
2138
                }
2139

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

2158
                for alias, real := range s.baseIndex {
6✔
2159
                        if real == linkScid {
6✔
2160
                                delete(s.baseIndex, alias)
3✔
2161
                        }
3✔
2162
                }
2163

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

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

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

3✔
2182
        s.indexMtx.RLock()
3✔
2183
        defer s.indexMtx.RUnlock()
3✔
2184

3✔
2185
        return s.getLink(chanID)
3✔
2186
}
3✔
2187

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

2199
        return link, nil
3✔
2200
}
2201

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

3✔
2207
        s.indexMtx.RLock()
3✔
2208
        defer s.indexMtx.RUnlock()
3✔
2209

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

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

2224
        return link, nil
3✔
2225
}
2226

2227
// getLinkByShortID attempts to return the link which possesses the target
2228
// short channel ID.
2229
//
2230
// NOTE: This MUST be called with the indexMtx held.
2231
func (s *Switch) getLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink, error) {
3✔
2232
        link, ok := s.forwardingIndex[chanID]
3✔
2233
        if !ok {
6✔
2234
                return nil, ErrChannelLinkNotFound
3✔
2235
        }
3✔
2236

2237
        return link, nil
3✔
2238
}
2239

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

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

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

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

2277
                // A mapping exists, so use baseScid to find the link in the
2278
                // forwardingIndex.
2279
                link, ok := s.forwardingIndex[baseScid]
3✔
2280
                if !ok {
3✔
2281
                        // Link not found, bail.
×
2282
                        return nil, ErrChannelLinkNotFound
×
2283
                }
×
2284

2285
                // Change the packet's outgoingChanID field so that errors are
2286
                // properly attributed.
2287
                pkt.outgoingChanID = baseScid
3✔
2288

3✔
2289
                // Return the link without checking if it's private or not.
3✔
2290
                return link, nil
3✔
2291
        }
2292

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

2306
                return link, nil
3✔
2307
        }
2308

2309
        // Fetch the link whose internal SCID is baseScid.
2310
        link, ok := s.forwardingIndex[baseScid]
3✔
2311
        if !ok {
3✔
2312
                // Link wasn't found, bail out.
×
2313
                return nil, ErrChannelLinkNotFound
×
2314
        }
×
2315

2316
        // If the link is unadvertised, we fail since the real SCID was used to
2317
        // forward over it and this is a channel where the option-scid-alias
2318
        // feature bit was negotiated.
2319
        if link.IsUnadvertised() {
3✔
2320
                log.Debugf("Link is unadvertised, chanID=%v, baseScid=%v",
×
2321
                        chanID, baseScid)
×
2322

×
2323
                return nil, ErrChannelLinkNotFound
×
2324
        }
×
2325

2326
        // The link is public so the confirmed SCID can be used to forward over
2327
        // it. We'll also replace pkt's outgoingChanID field so errors can
2328
        // properly be attributed in the calling function.
2329
        pkt.outgoingChanID = baseScid
3✔
2330
        return link, nil
3✔
2331
}
2332

2333
// HasActiveLink returns true if the given channel ID has a link in the link
2334
// index AND the link is eligible to forward.
2335
func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
3✔
2336
        s.indexMtx.RLock()
3✔
2337
        defer s.indexMtx.RUnlock()
3✔
2338

3✔
2339
        if link, ok := s.linkIndex[chanID]; ok {
6✔
2340
                return link.EligibleToForward()
3✔
2341
        }
3✔
2342

2343
        return false
3✔
2344
}
2345

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

2361
        // Check if the link is already stopping and grab the stop chan if it
2362
        // is.
2363
        stopChan, ok := s.linkStopIndex[chanID]
3✔
2364
        if !ok {
6✔
2365
                // If the link is non-nil, it is not currently stopping, so
3✔
2366
                // we'll add a stop chan to the linkStopIndex.
3✔
2367
                stopChan = make(chan struct{})
3✔
2368
                s.linkStopIndex[chanID] = stopChan
3✔
2369
        }
3✔
2370
        s.indexMtx.Unlock()
3✔
2371

3✔
2372
        if ok {
3✔
2373
                // If the stop chan exists, we will wait for it to be closed.
×
2374
                // Once it is closed, we will exit.
×
2375
                select {
×
2376
                case <-stopChan:
×
2377
                        return
×
2378
                case <-s.quit:
×
2379
                        return
×
2380
                }
2381
        }
2382

2383
        // Stop the link before removing it from the maps.
2384
        link.Stop()
3✔
2385

3✔
2386
        s.indexMtx.Lock()
3✔
2387
        _ = s.removeLink(chanID)
3✔
2388

3✔
2389
        // Close stopChan and remove this link from the linkStopIndex.
3✔
2390
        // Deleting from the index and removing from the link must be done
3✔
2391
        // in the same block while the mutex is held.
3✔
2392
        close(stopChan)
3✔
2393
        delete(s.linkStopIndex, chanID)
3✔
2394
        s.indexMtx.Unlock()
3✔
2395
}
2396

2397
// removeLink is used to remove and stop the channel link.
2398
//
2399
// NOTE: This MUST be called with the indexMtx held.
2400
func (s *Switch) removeLink(chanID lnwire.ChannelID) ChannelLink {
3✔
2401
        log.Infof("Removing channel link with ChannelID(%v)", chanID)
3✔
2402

3✔
2403
        link, err := s.getLink(chanID)
3✔
2404
        if err != nil {
3✔
2405
                return nil
×
2406
        }
×
2407

2408
        // Remove the channel from live link indexes.
2409
        delete(s.pendingLinkIndex, link.ChanID())
3✔
2410
        delete(s.linkIndex, link.ChanID())
3✔
2411
        delete(s.forwardingIndex, link.ShortChanID())
3✔
2412

3✔
2413
        // If the link has been added to the peer index, then we'll move to
3✔
2414
        // delete the entry within the index.
3✔
2415
        peerPub := link.PeerPubKey()
3✔
2416
        if peerIndex, ok := s.interfaceIndex[peerPub]; ok {
6✔
2417
                delete(peerIndex, link.ChanID())
3✔
2418

3✔
2419
                // If after deletion, there are no longer any links, then we'll
3✔
2420
                // remove the interface map all together.
3✔
2421
                if len(peerIndex) == 0 {
6✔
2422
                        delete(s.interfaceIndex, peerPub)
3✔
2423
                }
3✔
2424
        }
2425

2426
        return link
3✔
2427
}
2428

2429
// UpdateShortChanID locates the link with the passed-in chanID and updates the
2430
// underlying channel state. This is only used in zero-conf channels to allow
2431
// the confirmed SCID to be updated.
2432
func (s *Switch) UpdateShortChanID(chanID lnwire.ChannelID) error {
3✔
2433
        s.indexMtx.Lock()
3✔
2434
        defer s.indexMtx.Unlock()
3✔
2435

3✔
2436
        // Locate the target link in the link index. If no such link exists,
3✔
2437
        // then we will ignore the request.
3✔
2438
        link, ok := s.linkIndex[chanID]
3✔
2439
        if !ok {
3✔
2440
                return fmt.Errorf("link %v not found", chanID)
×
2441
        }
×
2442

2443
        // Try to update the link's underlying channel state, returning early
2444
        // if this update failed.
2445
        _, err := link.UpdateShortChanID()
3✔
2446
        if err != nil {
3✔
2447
                return err
×
2448
        }
×
2449

2450
        // Since the zero-conf channel is confirmed, we should populate the
2451
        // aliasToReal map and update the baseIndex.
2452
        aliases := link.getAliases()
3✔
2453

3✔
2454
        confirmedScid := link.confirmedScid()
3✔
2455

3✔
2456
        for _, alias := range aliases {
6✔
2457
                s.aliasToReal[alias] = confirmedScid
3✔
2458
        }
3✔
2459

2460
        s.baseIndex[confirmedScid] = link.ShortChanID()
3✔
2461

3✔
2462
        return nil
3✔
2463
}
2464

2465
// GetLinksByInterface fetches all the links connected to a particular node
2466
// identified by the serialized compressed form of its public key.
2467
func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
2468
        error) {
3✔
2469

3✔
2470
        s.indexMtx.RLock()
3✔
2471
        defer s.indexMtx.RUnlock()
3✔
2472

3✔
2473
        var handlers []ChannelUpdateHandler
3✔
2474

3✔
2475
        links, err := s.getLinks(hop)
3✔
2476
        if err != nil {
6✔
2477
                return nil, err
3✔
2478
        }
3✔
2479

2480
        // Range over the returned []ChannelLink to convert them into
2481
        // []ChannelUpdateHandler.
2482
        for _, link := range links {
6✔
2483
                handlers = append(handlers, link)
3✔
2484
        }
3✔
2485

2486
        return handlers, nil
3✔
2487
}
2488

2489
// GetLinksByPubkey fetches all the links connected to a particular node
2490
// identified by the serialized compressed form of its public key.
2491
func (s *Switch) GetLinksByPubkey(hop [33]byte) ([]ChannelInfoProvider,
2492
        error) {
3✔
2493

3✔
2494
        s.indexMtx.RLock()
3✔
2495
        defer s.indexMtx.RUnlock()
3✔
2496

3✔
2497
        links, err := s.getLinks(hop)
3✔
2498
        if err != nil {
3✔
NEW
2499
                return nil, err
×
NEW
2500
        }
×
2501

2502
        handlers := make([]ChannelInfoProvider, 0, len(links))
3✔
2503

3✔
2504
        // Range over the returned []ChannelLink to convert them into
3✔
2505
        // []ChannelUpdateHandler.
3✔
2506
        for _, link := range links {
6✔
2507
                handlers = append(handlers, link)
3✔
2508
        }
3✔
2509

2510
        return handlers, nil
3✔
2511
}
2512

2513
// getLinks is function which returns the channel links of the peer by hop
2514
// destination id.
2515
//
2516
// NOTE: This MUST be called with the indexMtx held.
2517
func (s *Switch) getLinks(destination [33]byte) ([]ChannelLink, error) {
3✔
2518
        links, ok := s.interfaceIndex[destination]
3✔
2519
        if !ok {
6✔
2520
                return nil, ErrNoLinksFound
3✔
2521
        }
3✔
2522

2523
        channelLinks := make([]ChannelLink, 0, len(links))
3✔
2524
        for _, link := range links {
6✔
2525
                channelLinks = append(channelLinks, link)
3✔
2526
        }
3✔
2527

2528
        return channelLinks, nil
3✔
2529
}
2530

2531
// CircuitModifier returns a reference to subset of the interfaces provided by
2532
// the circuit map, to allow links to open and close circuits.
2533
func (s *Switch) CircuitModifier() CircuitModifier {
3✔
2534
        return s.circuits
3✔
2535
}
3✔
2536

2537
// CircuitLookup returns a reference to subset of the interfaces provided by the
2538
// circuit map, to allow looking up circuits.
2539
func (s *Switch) CircuitLookup() CircuitLookup {
3✔
2540
        return s.circuits
3✔
2541
}
3✔
2542

2543
// commitCircuits persistently adds a circuit to the switch's circuit map.
2544
func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
2545
        *CircuitFwdActions, error) {
×
2546

×
2547
        return s.circuits.CommitCircuits(circuits...)
×
2548
}
×
2549

2550
// FlushForwardingEvents flushes out the set of pending forwarding events to
2551
// the persistent log. This will be used by the switch to periodically flush
2552
// out the set of forwarding events to disk. External callers can also use this
2553
// method to ensure all data is flushed to dis before querying the log.
2554
func (s *Switch) FlushForwardingEvents() error {
3✔
2555
        // First, we'll obtain a copy of the current set of pending forwarding
3✔
2556
        // events.
3✔
2557
        s.fwdEventMtx.Lock()
3✔
2558

3✔
2559
        // If we won't have any forwarding events, then we can exit early.
3✔
2560
        if len(s.pendingFwdingEvents) == 0 {
6✔
2561
                s.fwdEventMtx.Unlock()
3✔
2562
                return nil
3✔
2563
        }
3✔
2564

2565
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
3✔
2566
        copy(events[:], s.pendingFwdingEvents[:])
3✔
2567

3✔
2568
        // With the copy obtained, we can now clear out the header pointer of
3✔
2569
        // the current slice. This way, we can re-use the underlying storage
3✔
2570
        // allocated for the slice.
3✔
2571
        s.pendingFwdingEvents = s.pendingFwdingEvents[:0]
3✔
2572
        s.fwdEventMtx.Unlock()
3✔
2573

3✔
2574
        // Finally, we'll write out the copied events to the persistent
3✔
2575
        // forwarding log.
3✔
2576
        return s.cfg.FwdingLog.AddForwardingEvents(events)
3✔
2577
}
2578

2579
// BestHeight returns the best height known to the switch.
2580
func (s *Switch) BestHeight() uint32 {
3✔
2581
        return atomic.LoadUint32(&s.bestHeight)
3✔
2582
}
3✔
2583

2584
// dustExceedsFeeThreshold takes in a ChannelLink, HTLC amount, and a boolean
2585
// to determine whether the default fee threshold has been exceeded. This
2586
// heuristic takes into account the trimmed-to-dust mechanism. The sum of the
2587
// commitment's dust with the mailbox's dust with the amount is checked against
2588
// the fee exposure threshold. If incoming is true, then the amount is not
2589
// included in the sum as it was already included in the commitment's dust. A
2590
// boolean is returned telling the caller whether the HTLC should be failed
2591
// back.
2592
func (s *Switch) dustExceedsFeeThreshold(link ChannelLink,
2593
        amount lnwire.MilliSatoshi, incoming bool) bool {
3✔
2594

3✔
2595
        // Retrieve the link's current commitment feerate and dustClosure.
3✔
2596
        feeRate := link.getFeeRate()
3✔
2597
        isDust := link.getDustClosure()
3✔
2598

3✔
2599
        // Evaluate if the HTLC is dust on either sides' commitment.
3✔
2600
        isLocalDust := isDust(
3✔
2601
                feeRate, incoming, lntypes.Local, amount.ToSatoshis(),
3✔
2602
        )
3✔
2603
        isRemoteDust := isDust(
3✔
2604
                feeRate, incoming, lntypes.Remote, amount.ToSatoshis(),
3✔
2605
        )
3✔
2606

3✔
2607
        if !(isLocalDust || isRemoteDust) {
6✔
2608
                // If the HTLC is not dust on either commitment, it's fine to
3✔
2609
                // forward.
3✔
2610
                return false
3✔
2611
        }
3✔
2612

2613
        // Fetch the dust sums currently in the mailbox for this link.
2614
        cid := link.ChanID()
3✔
2615
        sid := link.ShortChanID()
3✔
2616
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
3✔
2617
        localMailDust, remoteMailDust := mailbox.DustPackets()
3✔
2618

3✔
2619
        // If the htlc is dust on the local commitment, we'll obtain the dust
3✔
2620
        // sum for it.
3✔
2621
        if isLocalDust {
6✔
2622
                localSum := link.getDustSum(
3✔
2623
                        lntypes.Local, fn.None[chainfee.SatPerKWeight](),
3✔
2624
                )
3✔
2625
                localSum += localMailDust
3✔
2626

3✔
2627
                // Optionally include the HTLC amount only for outgoing
3✔
2628
                // HTLCs.
3✔
2629
                if !incoming {
6✔
2630
                        localSum += amount
3✔
2631
                }
3✔
2632

2633
                // Finally check against the defined fee threshold.
2634
                if localSum > s.cfg.MaxFeeExposure {
3✔
2635
                        return true
×
2636
                }
×
2637
        }
2638

2639
        // Also check if the htlc is dust on the remote commitment, if we've
2640
        // reached this point.
2641
        if isRemoteDust {
6✔
2642
                remoteSum := link.getDustSum(
3✔
2643
                        lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
3✔
2644
                )
3✔
2645
                remoteSum += remoteMailDust
3✔
2646

3✔
2647
                // Optionally include the HTLC amount only for outgoing
3✔
2648
                // HTLCs.
3✔
2649
                if !incoming {
6✔
2650
                        remoteSum += amount
3✔
2651
                }
3✔
2652

2653
                // Finally check against the defined fee threshold.
2654
                if remoteSum > s.cfg.MaxFeeExposure {
3✔
2655
                        return true
×
2656
                }
×
2657
        }
2658

2659
        // If we reached this point, this HTLC is fine to forward.
2660
        return false
3✔
2661
}
2662

2663
// failMailboxUpdate is passed to the mailbox orchestrator which in turn passes
2664
// it to individual mailboxes. It allows the mailboxes to construct a
2665
// FailureMessage when failing back HTLC's due to expiry and may include an
2666
// alias in the ShortChannelID field. The outgoingScid is the SCID originally
2667
// used in the onion. The mailboxScid is the SCID that the mailbox and link
2668
// use. The mailboxScid is only used in the non-alias case, so it is always
2669
// the confirmed SCID.
2670
func (s *Switch) failMailboxUpdate(outgoingScid,
2671
        mailboxScid lnwire.ShortChannelID) lnwire.FailureMessage {
3✔
2672

3✔
2673
        // Try to use the failAliasUpdate function in case this is a channel
3✔
2674
        // that uses aliases. If it returns nil, we'll fallback to the original
3✔
2675
        // pre-alias behavior.
3✔
2676
        update := s.failAliasUpdate(outgoingScid, false)
3✔
2677
        if update == nil {
6✔
2678
                // Execute the fallback behavior.
3✔
2679
                var err error
3✔
2680
                update, err = s.cfg.FetchLastChannelUpdate(mailboxScid)
3✔
2681
                if err != nil {
3✔
2682
                        return &lnwire.FailTemporaryNodeFailure{}
×
2683
                }
×
2684
        }
2685

2686
        return lnwire.NewTemporaryChannelFailure(update)
3✔
2687
}
2688

2689
// failAliasUpdate prepares a ChannelUpdate for a failed incoming or outgoing
2690
// HTLC on a channel where the option-scid-alias feature bit was negotiated. If
2691
// the associated channel is not one of these, this function will return nil
2692
// and the caller is expected to handle this properly. In this case, a return
2693
// to the original non-alias behavior is expected.
2694
func (s *Switch) failAliasUpdate(scid lnwire.ShortChannelID,
2695
        incoming bool) *lnwire.ChannelUpdate1 {
3✔
2696

3✔
2697
        // This function does not defer the unlocking because of the database
3✔
2698
        // lookups for ChannelUpdate.
3✔
2699
        s.indexMtx.RLock()
3✔
2700

3✔
2701
        if s.cfg.IsAlias(scid) {
6✔
2702
                // The alias SCID was used. In the incoming case this means
3✔
2703
                // the channel is zero-conf as the link sets the scid. In the
3✔
2704
                // outgoing case, the sender set the scid to use and may be
3✔
2705
                // either the alias or the confirmed one, if it exists.
3✔
2706
                realScid, ok := s.aliasToReal[scid]
3✔
2707
                if !ok {
3✔
2708
                        // The real, confirmed SCID does not exist yet. Find
×
2709
                        // the "base" SCID that the link uses via the
×
2710
                        // baseIndex. If we can't find it, return nil. This
×
2711
                        // means the channel is zero-conf.
×
2712
                        baseScid, ok := s.baseIndex[scid]
×
2713
                        s.indexMtx.RUnlock()
×
2714
                        if !ok {
×
2715
                                return nil
×
2716
                        }
×
2717

2718
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2719
                        if err != nil {
×
2720
                                return nil
×
2721
                        }
×
2722

2723
                        // Replace the baseScid with the passed-in alias.
2724
                        update.ShortChannelID = scid
×
2725
                        sig, err := s.cfg.SignAliasUpdate(update)
×
2726
                        if err != nil {
×
2727
                                return nil
×
2728
                        }
×
2729

2730
                        update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2731
                        if err != nil {
×
2732
                                return nil
×
2733
                        }
×
2734

2735
                        return update
×
2736
                }
2737

2738
                s.indexMtx.RUnlock()
3✔
2739

3✔
2740
                // Fetch the SCID via the confirmed SCID and replace it with
3✔
2741
                // the alias.
3✔
2742
                update, err := s.cfg.FetchLastChannelUpdate(realScid)
3✔
2743
                if err != nil {
6✔
2744
                        return nil
3✔
2745
                }
3✔
2746

2747
                // In the incoming case, we want to ensure that we don't leak
2748
                // the UTXO in case the channel is private. In the outgoing
2749
                // case, since the alias was used, we do the same thing.
2750
                update.ShortChannelID = scid
3✔
2751
                sig, err := s.cfg.SignAliasUpdate(update)
3✔
2752
                if err != nil {
3✔
2753
                        return nil
×
2754
                }
×
2755

2756
                update.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
2757
                if err != nil {
3✔
2758
                        return nil
×
2759
                }
×
2760

2761
                return update
3✔
2762
        }
2763

2764
        // If the confirmed SCID is not in baseIndex, this is not an
2765
        // option-scid-alias or zero-conf channel.
2766
        baseScid, ok := s.baseIndex[scid]
3✔
2767
        if !ok {
6✔
2768
                s.indexMtx.RUnlock()
3✔
2769
                return nil
3✔
2770
        }
3✔
2771

2772
        // Fetch the link so we can get an alias to use in the ShortChannelID
2773
        // of the ChannelUpdate.
2774
        link, ok := s.forwardingIndex[baseScid]
×
2775
        s.indexMtx.RUnlock()
×
2776
        if !ok {
×
2777
                // This should never happen, but if it does for some reason,
×
2778
                // fallback to the old behavior.
×
2779
                return nil
×
2780
        }
×
2781

2782
        aliases := link.getAliases()
×
2783
        if len(aliases) == 0 {
×
2784
                // This should never happen, but if it does, fallback.
×
2785
                return nil
×
2786
        }
×
2787

2788
        // Fetch the ChannelUpdate via the real, confirmed SCID.
2789
        update, err := s.cfg.FetchLastChannelUpdate(scid)
×
2790
        if err != nil {
×
2791
                return nil
×
2792
        }
×
2793

2794
        // The incoming case will replace the ShortChannelID in the retrieved
2795
        // ChannelUpdate with the alias to ensure no privacy leak occurs. This
2796
        // would happen if a private non-zero-conf option-scid-alias
2797
        // feature-bit channel leaked its UTXO here rather than supplying an
2798
        // alias. In the outgoing case, the confirmed SCID was actually used
2799
        // for forwarding in the onion, so no replacement is necessary as the
2800
        // sender knows the scid.
2801
        if incoming {
×
2802
                // We will replace and sign the update with the first alias.
×
2803
                // Since this happens on the incoming side, it's not actually
×
2804
                // possible to know what the sender used in the onion.
×
2805
                update.ShortChannelID = aliases[0]
×
2806
                sig, err := s.cfg.SignAliasUpdate(update)
×
2807
                if err != nil {
×
2808
                        return nil
×
2809
                }
×
2810

2811
                update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2812
                if err != nil {
×
2813
                        return nil
×
2814
                }
×
2815
        }
2816

2817
        return update
×
2818
}
2819

2820
// AddAliasForLink instructs the Switch to update its in-memory maps to reflect
2821
// that a link has a new alias.
2822
func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
2823
        alias lnwire.ShortChannelID) error {
×
2824

×
2825
        // Fetch the link so that we can update the underlying channel's set of
×
2826
        // aliases.
×
2827
        s.indexMtx.RLock()
×
2828
        link, err := s.getLink(chanID)
×
2829
        s.indexMtx.RUnlock()
×
2830
        if err != nil {
×
2831
                return err
×
2832
        }
×
2833

2834
        // If the link is a channel where the option-scid-alias feature bit was
2835
        // not negotiated, we'll return an error.
2836
        if !link.negotiatedAliasFeature() {
×
2837
                return fmt.Errorf("attempted to update non-alias channel")
×
2838
        }
×
2839

2840
        linkScid := link.ShortChanID()
×
2841

×
2842
        // We'll update the maps so the Switch includes this alias in its
×
2843
        // forwarding decisions.
×
2844
        if link.isZeroConf() {
×
2845
                if link.zeroConfConfirmed() {
×
2846
                        // If the channel has confirmed on-chain, we'll
×
2847
                        // add this alias to the aliasToReal map.
×
2848
                        confirmedScid := link.confirmedScid()
×
2849

×
2850
                        s.aliasToReal[alias] = confirmedScid
×
2851
                }
×
2852

2853
                // Add this alias to the baseIndex mapping.
2854
                s.baseIndex[alias] = linkScid
×
2855
        } else if link.negotiatedAliasFeature() {
×
2856
                // The channel is confirmed, so we'll populate the aliasToReal
×
2857
                // and baseIndex maps.
×
2858
                s.aliasToReal[alias] = linkScid
×
2859
                s.baseIndex[alias] = linkScid
×
2860
        }
×
2861

2862
        return nil
×
2863
}
2864

2865
// handlePacketAdd handles forwarding an Add packet.
2866
func (s *Switch) handlePacketAdd(packet *htlcPacket,
2867
        htlc *lnwire.UpdateAddHTLC) error {
3✔
2868

3✔
2869
        // Check if the node is set to reject all onward HTLCs and also make
3✔
2870
        // sure that HTLC is not from the source node.
3✔
2871
        if s.cfg.RejectHTLC {
6✔
2872
                failure := NewDetailedLinkError(
3✔
2873
                        &lnwire.FailChannelDisabled{},
3✔
2874
                        OutgoingFailureForwardsDisabled,
3✔
2875
                )
3✔
2876

3✔
2877
                return s.failAddPacket(packet, failure)
3✔
2878
        }
3✔
2879

2880
        // Before we attempt to find a non-strict forwarding path for this
2881
        // htlc, check whether the htlc is being routed over the same incoming
2882
        // and outgoing channel. If our node does not allow forwards of this
2883
        // nature, we fail the htlc early. This check is in place to disallow
2884
        // inefficiently routed htlcs from locking up our balance. With
2885
        // channels where the option-scid-alias feature was negotiated, we also
2886
        // have to be sure that the IDs aren't the same since one or both could
2887
        // be an alias.
2888
        linkErr := s.checkCircularForward(
3✔
2889
                packet.incomingChanID, packet.outgoingChanID,
3✔
2890
                s.cfg.AllowCircularRoute, htlc.PaymentHash,
3✔
2891
        )
3✔
2892
        if linkErr != nil {
3✔
2893
                return s.failAddPacket(packet, linkErr)
×
2894
        }
×
2895

2896
        s.indexMtx.RLock()
3✔
2897
        targetLink, err := s.getLinkByMapping(packet)
3✔
2898
        if err != nil {
6✔
2899
                s.indexMtx.RUnlock()
3✔
2900

3✔
2901
                log.Debugf("unable to find link with "+
3✔
2902
                        "destination %v", packet.outgoingChanID)
3✔
2903

3✔
2904
                // If packet was forwarded from another channel link than we
3✔
2905
                // should notify this link that some error occurred.
3✔
2906
                linkError := NewLinkError(
3✔
2907
                        &lnwire.FailUnknownNextPeer{},
3✔
2908
                )
3✔
2909

3✔
2910
                return s.failAddPacket(packet, linkError)
3✔
2911
        }
3✔
2912
        targetPeerKey := targetLink.PeerPubKey()
3✔
2913
        interfaceLinks, _ := s.getLinks(targetPeerKey)
3✔
2914
        s.indexMtx.RUnlock()
3✔
2915

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

3✔
2922
        // Find all destination channel links with appropriate bandwidth.
3✔
2923
        var destinations []ChannelLink
3✔
2924
        for _, link := range interfaceLinks {
6✔
2925
                var failure *LinkError
3✔
2926

3✔
2927
                // We'll skip any links that aren't yet eligible for
3✔
2928
                // forwarding.
3✔
2929
                if !link.EligibleToForward() {
3✔
2930
                        failure = NewDetailedLinkError(
×
2931
                                &lnwire.FailUnknownNextPeer{},
×
2932
                                OutgoingFailureLinkNotEligible,
×
2933
                        )
×
2934
                } else {
3✔
2935
                        // We'll ensure that the HTLC satisfies the current
3✔
2936
                        // forwarding conditions of this target link.
3✔
2937
                        currentHeight := atomic.LoadUint32(&s.bestHeight)
3✔
2938
                        failure = link.CheckHtlcForward(
3✔
2939
                                htlc.PaymentHash, packet.incomingAmount,
3✔
2940
                                packet.amount, packet.incomingTimeout,
3✔
2941
                                packet.outgoingTimeout, packet.inboundFee,
3✔
2942
                                currentHeight, packet.originalOutgoingChanID,
3✔
2943
                                htlc.CustomRecords,
3✔
2944
                        )
3✔
2945
                }
3✔
2946

2947
                // If this link can forward the htlc, add it to the set of
2948
                // destinations.
2949
                if failure == nil {
6✔
2950
                        destinations = append(destinations, link)
3✔
2951
                        continue
3✔
2952
                }
2953

2954
                linkErrs[link.ShortChanID()] = failure
3✔
2955
        }
2956

2957
        // If we had a forwarding failure due to the HTLC not satisfying the
2958
        // current policy, then we'll send back an error, but ensure we send
2959
        // back the error sourced at the *target* link.
2960
        if len(destinations) == 0 {
6✔
2961
                // At this point, some or all of the links rejected the HTLC so
3✔
2962
                // we couldn't forward it. So we'll try to look up the error
3✔
2963
                // that came from the source.
3✔
2964
                linkErr, ok := linkErrs[packet.outgoingChanID]
3✔
2965
                if !ok {
3✔
2966
                        // If we can't find the error of the source, then we'll
×
2967
                        // return an unknown next peer, though this should
×
2968
                        // never happen.
×
2969
                        linkErr = NewLinkError(
×
2970
                                &lnwire.FailUnknownNextPeer{},
×
2971
                        )
×
2972
                        log.Warnf("unable to find err source for "+
×
2973
                                "outgoing_link=%v, errors=%v",
×
2974
                                packet.outgoingChanID,
×
2975
                                lnutils.SpewLogClosure(linkErrs))
×
2976
                }
×
2977

2978
                log.Tracef("incoming HTLC(%x) violated "+
3✔
2979
                        "target outgoing link (id=%v) policy: %v",
3✔
2980
                        htlc.PaymentHash[:], packet.outgoingChanID,
3✔
2981
                        linkErr)
3✔
2982

3✔
2983
                return s.failAddPacket(packet, linkErr)
3✔
2984
        }
2985

2986
        // Choose a random link out of the set of links that can forward this
2987
        // htlc. The reason for randomization is to evenly distribute the htlc
2988
        // load without making assumptions about what the best channel is.
2989
        //nolint:gosec
2990
        destination := destinations[rand.Intn(len(destinations))]
3✔
2991

3✔
2992
        // Retrieve the incoming link by its ShortChannelID. Note that the
3✔
2993
        // incomingChanID is never set to hop.Source here.
3✔
2994
        s.indexMtx.RLock()
3✔
2995
        incomingLink, err := s.getLinkByShortID(packet.incomingChanID)
3✔
2996
        s.indexMtx.RUnlock()
3✔
2997
        if err != nil {
3✔
2998
                // If we couldn't find the incoming link, we can't evaluate the
×
2999
                // incoming's exposure to dust, so we just fail the HTLC back.
×
3000
                linkErr := NewLinkError(
×
3001
                        &lnwire.FailTemporaryChannelFailure{},
×
3002
                )
×
3003

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

3007
        // Evaluate whether this HTLC would increase our fee exposure over the
3008
        // threshold on the incoming link. If it does, fail it backwards.
3009
        if s.dustExceedsFeeThreshold(
3✔
3010
                incomingLink, packet.incomingAmount, true,
3✔
3011
        ) {
3✔
3012
                // The incoming dust exceeds the threshold, so we fail the add
×
3013
                // back.
×
3014
                linkErr := NewLinkError(
×
3015
                        &lnwire.FailTemporaryChannelFailure{},
×
3016
                )
×
3017

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

3021
        // Also evaluate whether this HTLC would increase our fee exposure over
3022
        // the threshold on the destination link. If it does, fail it back.
3023
        if s.dustExceedsFeeThreshold(
3✔
3024
                destination, packet.amount, false,
3✔
3025
        ) {
3✔
3026
                // The outgoing dust exceeds the threshold, so we fail the add
×
3027
                // back.
×
3028
                linkErr := NewLinkError(
×
3029
                        &lnwire.FailTemporaryChannelFailure{},
×
3030
                )
×
3031

×
3032
                return s.failAddPacket(packet, linkErr)
×
3033
        }
×
3034

3035
        // Send the packet to the destination channel link which manages the
3036
        // channel.
3037
        packet.outgoingChanID = destination.ShortChanID()
3✔
3038

3✔
3039
        return destination.handleSwitchPacket(packet)
3✔
3040
}
3041

3042
// handlePacketSettle handles forwarding a settle packet.
3043
func (s *Switch) handlePacketSettle(packet *htlcPacket) error {
3✔
3044
        // If the source of this packet has not been set, use the circuit map
3✔
3045
        // to lookup the origin.
3✔
3046
        circuit, err := s.closeCircuit(packet)
3✔
3047

3✔
3048
        // If the circuit is in the process of closing, we will return a nil as
3✔
3049
        // there's another packet handling undergoing.
3✔
3050
        if errors.Is(err, ErrCircuitClosing) {
6✔
3051
                log.Debugf("Circuit is closing for packet=%v", packet)
3✔
3052
                return nil
3✔
3053
        }
3✔
3054

3055
        // Exit early if there's another error.
3056
        if err != nil {
3✔
3057
                return err
×
3058
        }
×
3059

3060
        // closeCircuit returns a nil circuit when a settle packet returns an
3061
        // ErrUnknownCircuit error upon the inner call to CloseCircuit.
3062
        //
3063
        // NOTE: We can only get a nil circuit when it has already been deleted
3064
        // and when `UpdateFulfillHTLC` is received. After which `RevokeAndAck`
3065
        // is received, which invokes `processRemoteSettleFails` in its link.
3066
        if circuit == nil {
6✔
3067
                log.Debugf("Circuit already closed for packet=%v", packet)
3✔
3068
                return nil
3✔
3069
        }
3✔
3070

3071
        localHTLC := packet.incomingChanID == hop.Source
3✔
3072

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

3✔
3085
                // If this is a locally initiated HTLC, there's no need to
3✔
3086
                // forward it so we exit.
3✔
3087
                return nil
3✔
3088
        }
3✔
3089

3090
        // If this is an HTLC settle, and it wasn't from a locally initiated
3091
        // HTLC, then we'll log a forwarding event so we can flush it to disk
3092
        // later.
3093
        if circuit.Outgoing != nil {
6✔
3094
                log.Infof("Forwarded HTLC(%x) of %v (fee: %v) "+
3✔
3095
                        "from IncomingChanID(%v) to OutgoingChanID(%v)",
3✔
3096
                        circuit.PaymentHash[:], circuit.OutgoingAmount,
3✔
3097
                        circuit.IncomingAmount-circuit.OutgoingAmount,
3✔
3098
                        circuit.Incoming.ChanID, circuit.Outgoing.ChanID)
3✔
3099

3✔
3100
                s.fwdEventMtx.Lock()
3✔
3101
                s.pendingFwdingEvents = append(
3✔
3102
                        s.pendingFwdingEvents,
3✔
3103
                        channeldb.ForwardingEvent{
3✔
3104
                                Timestamp:      time.Now(),
3✔
3105
                                IncomingChanID: circuit.Incoming.ChanID,
3✔
3106
                                OutgoingChanID: circuit.Outgoing.ChanID,
3✔
3107
                                AmtIn:          circuit.IncomingAmount,
3✔
3108
                                AmtOut:         circuit.OutgoingAmount,
3✔
3109
                        },
3✔
3110
                )
3✔
3111
                s.fwdEventMtx.Unlock()
3✔
3112
        }
3✔
3113

3114
        // Deliver this packet.
3115
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3116
}
3117

3118
// handlePacketFail handles forwarding a fail packet.
3119
func (s *Switch) handlePacketFail(packet *htlcPacket,
3120
        htlc *lnwire.UpdateFailHTLC) error {
3✔
3121

3✔
3122
        // If the source of this packet has not been set, use the circuit map
3✔
3123
        // to lookup the origin.
3✔
3124
        circuit, err := s.closeCircuit(packet)
3✔
3125
        if err != nil {
3✔
3126
                return err
×
3127
        }
×
3128

3129
        // If this is a locally initiated HTLC, we need to handle the packet by
3130
        // storing the network result.
3131
        //
3132
        // A blank IncomingChanID in a circuit indicates that it is a pending
3133
        // user-initiated payment.
3134
        //
3135
        // NOTE: `closeCircuit` modifies the state of `packet`.
3136
        if packet.incomingChanID == hop.Source {
6✔
3137
                // TODO(yy): remove the goroutine and send back the error here.
3✔
3138
                s.wg.Add(1)
3✔
3139
                go s.handleLocalResponse(packet)
3✔
3140

3✔
3141
                // If this is a locally initiated HTLC, there's no need to
3✔
3142
                // forward it so we exit.
3✔
3143
                return nil
3✔
3144
        }
3✔
3145

3146
        // Exit early if this hasSource is true. This flag is only set via
3147
        // mailbox's `FailAdd`. This method has two callsites,
3148
        // - the packet has timed out after `MailboxDeliveryTimeout`, defaults
3149
        //   to 1 min.
3150
        // - the HTLC fails the validation in `channel.AddHTLC`.
3151
        // In either case, the `Reason` field is populated. Thus there's no
3152
        // need to proceed and extract the failure reason below.
3153
        if packet.hasSource {
3✔
3154
                // Deliver this packet.
×
3155
                return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
×
3156
        }
×
3157

3158
        // HTLC resolutions and messages restored from disk don't have the
3159
        // obfuscator set from the original htlc add packet - set it here for
3160
        // use in blinded errors.
3161
        packet.obfuscator = circuit.ErrorEncrypter
3✔
3162

3✔
3163
        switch {
3✔
3164
        // No message to encrypt, locally sourced payment.
3165
        case circuit.ErrorEncrypter == nil:
×
3166
                // TODO(yy) further check this case as we shouldn't end up here
3167
                // as `isLocal` is already false.
3168

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

3183
        // Alternatively, if the remote party sends us an
3184
        // UpdateFailMalformedHTLC, then we'll need to convert this into a
3185
        // proper well formatted onion error as there's no HMAC currently.
3186
        case packet.convertedError:
3✔
3187
                log.Infof("Converting malformed HTLC error for circuit for "+
3✔
3188
                        "Circuit(%x: (%s, %d) <-> (%s, %d))",
3✔
3189
                        packet.circuit.PaymentHash,
3✔
3190
                        packet.incomingChanID, packet.incomingHTLCID,
3✔
3191
                        packet.outgoingChanID, packet.outgoingHTLCID)
3✔
3192

3✔
3193
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
3✔
3194
                        htlc.Reason,
3✔
3195
                )
3✔
3196

3197
        default:
3✔
3198
                // Otherwise, it's a forwarded error, so we'll perform a
3✔
3199
                // wrapper encryption as normal.
3✔
3200
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
3✔
3201
                        htlc.Reason,
3✔
3202
                )
3✔
3203
        }
3204

3205
        // Deliver this packet.
3206
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3207
}
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