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

lightningnetwork / lnd / 15782265189

20 Jun 2025 03:23PM UTC coverage: 68.14% (-0.003%) from 68.143%
15782265189

Pull #9958

github

web-flow
Merge ae1a1d1ba into 7857d2c6a
Pull Request #9958: improve CloseChannel docs

134478 of 197355 relevant lines covered (68.14%)

22170.18 hits per line

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

82.7
/htlcswitch/switch.go
1
package htlcswitch
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
        errChan chan error
412
}
413

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

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

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

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

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

451
        return false, nil
3✔
452
}
453

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

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

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

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

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

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

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

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

533
        return resultChan, nil
308✔
534
}
535

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

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

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

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

7✔
581
                return linkErr
7✔
582
        }
7✔
583

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

823
        return nil
89✔
824
}
825

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

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

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

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

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

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

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

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

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

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

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

920
        // Ensure that the htlc satisfies the outgoing channel policy.
921
        currentHeight := atomic.LoadUint32(&s.bestHeight)
418✔
922
        htlcErr := link.CheckHtlcTransit(
418✔
923
                htlc.PaymentHash, htlc.Amount, htlc.Expiry, currentHeight,
418✔
924
                htlc.CustomRecords,
418✔
925
        )
418✔
926
        if htlcErr != nil {
423✔
927
                log.Errorf("Link %v policy for local forward not "+
5✔
928
                        "satisfied", pkt.outgoingChanID)
5✔
929
                return nil, htlcErr
5✔
930
        }
5✔
931
        return link, nil
415✔
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) {
307✔
947
        defer s.wg.Done()
307✔
948

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

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

307✔
960
        // Store the result to the db. This will also notify subscribers about
307✔
961
        // the result.
307✔
962
        if err := s.networkResults.storeResult(attemptID, n); err != nil {
307✔
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 {
428✔
976
                if err := s.ackSettleFail(*pkt.destRef); err != nil {
121✔
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 {
307✔
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)
307✔
998
        eventType := getEventType(pkt)
307✔
999

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

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

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

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

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

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

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

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

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

127✔
1055
        switch {
127✔
1056

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

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

×
1078
                        return linkError
×
1079
                }
×
1080

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

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

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

3✔
1098
                return linkError
3✔
1099

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

1✔
1111
                        return ErrUnreadableFailureMessage
1✔
1112
                }
1✔
1113

1114
                return failure
121✔
1115
        }
1116
}
1117

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1271
        return failure
29✔
1272
}
1273

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

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

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

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

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

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

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

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

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

339✔
1331
                return circuit, nil
339✔
1332

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

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

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

×
1359
                        return nil, err
×
1360
                }
×
1361

1362
                return nil, nil
194✔
1363

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

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

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

1393
        var paymentHash lntypes.Hash
317✔
1394

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

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

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

×
1412
                return err
×
1413
        }
×
1414

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

317✔
1419
        return nil
317✔
1420
}
1421

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

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

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

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

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

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

210✔
1471
        defer func() {
420✔
1472
                s.blockEpochStream.Cancel()
210✔
1473

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

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

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

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

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

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

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

210✔
1536
out:
210✔
1537
        for {
1,046✔
1538

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1791
        return nil
210✔
1792
}
1793

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

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

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

1821
                        continue
4✔
1822
                }
1823

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

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

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

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

1852
        return nil
210✔
1853
}
1854

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

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

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

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

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

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

1896
        return nil
210✔
1897
}
1898

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

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

1916
        return fwdPkgs, nil
132✔
1917
}
1918

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

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

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

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

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

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

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

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

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

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

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

312✔
2015
        return nil
312✔
2016
}
2017

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

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

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

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

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

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

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

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

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

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

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

2074
        return nil
338✔
2075
}
2076

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2191
        return link, nil
3,572✔
2192
}
2193

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

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

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

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

2216
        return link, nil
3✔
2217
}
2218

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

2229
        return link, nil
479✔
2230
}
2231

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

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

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

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

2269
                // A mapping exists, so use baseScid to find the link in the
2270
                // forwardingIndex.
2271
                link, ok := s.forwardingIndex[baseScid]
18✔
2272
                if !ok {
18✔
2273
                        log.Debugf("Forwarding index not found using "+
×
2274
                                "baseScid=%v", baseScid)
×
2275

×
2276
                        // Link not found, bail.
×
2277
                        return nil, ErrChannelLinkNotFound
×
2278
                }
×
2279

2280
                // Change the packet's outgoingChanID field so that errors are
2281
                // properly attributed.
2282
                pkt.outgoingChanID = baseScid
18✔
2283

18✔
2284
                // Return the link without checking if it's private or not.
18✔
2285
                return link, nil
18✔
2286
        }
2287

2288
        // The outgoingChanID is a confirmed SCID. Attempt to fetch the base
2289
        // SCID from baseIndex.
2290
        baseScid, ok := s.baseIndex[chanID]
68✔
2291
        if !ok {
129✔
2292
                // outgoingChanID is not a key in base index meaning this
61✔
2293
                // channel did not have the option-scid-alias feature bit
61✔
2294
                // negotiated. We'll fetch the link and return it.
61✔
2295
                link, ok := s.forwardingIndex[chanID]
61✔
2296
                if !ok {
66✔
2297
                        log.Debugf("Forwarding index not found using "+
5✔
2298
                                "chanID=%v", chanID)
5✔
2299

5✔
2300
                        // The link wasn't found, bail out.
5✔
2301
                        return nil, ErrChannelLinkNotFound
5✔
2302
                }
5✔
2303

2304
                return link, nil
59✔
2305
        }
2306

2307
        // Fetch the link whose internal SCID is baseScid.
2308
        link, ok := s.forwardingIndex[baseScid]
10✔
2309
        if !ok {
10✔
2310
                log.Debugf("Forwarding index not found using baseScid=%v",
×
2311
                        baseScid)
×
2312

×
2313
                // Link wasn't found, bail out.
×
2314
                return nil, ErrChannelLinkNotFound
×
2315
        }
×
2316

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

2✔
2324
                return nil, ErrChannelLinkNotFound
2✔
2325
        }
2✔
2326

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

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

5✔
2340
        if link, ok := s.linkIndex[chanID]; ok {
10✔
2341
                return link.EligibleToForward()
5✔
2342
        }
5✔
2343

2344
        return false
3✔
2345
}
2346

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

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

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

2384
        // Stop the link before removing it from the maps.
2385
        link.Stop()
21✔
2386

21✔
2387
        s.indexMtx.Lock()
21✔
2388
        _ = s.removeLink(chanID)
21✔
2389

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

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

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

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

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

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

2427
        return link
314✔
2428
}
2429

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

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

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

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

4✔
2455
        confirmedScid := link.confirmedScid()
4✔
2456

4✔
2457
        for _, alias := range aliases {
9✔
2458
                s.aliasToReal[alias] = confirmedScid
5✔
2459
        }
5✔
2460

2461
        s.baseIndex[confirmedScid] = link.ShortChanID()
4✔
2462

4✔
2463
        return nil
4✔
2464
}
2465

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

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

3✔
2474
        var handlers []ChannelUpdateHandler
3✔
2475

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

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

2487
        return handlers, nil
3✔
2488
}
2489

2490
// getLinks is function which returns the channel links of the peer by hop
2491
// destination id.
2492
//
2493
// NOTE: This MUST be called with the indexMtx held.
2494
func (s *Switch) getLinks(destination [33]byte) ([]ChannelLink, error) {
79✔
2495
        links, ok := s.interfaceIndex[destination]
79✔
2496
        if !ok {
82✔
2497
                return nil, ErrNoLinksFound
3✔
2498
        }
3✔
2499

2500
        channelLinks := make([]ChannelLink, 0, len(links))
79✔
2501
        for _, link := range links {
162✔
2502
                channelLinks = append(channelLinks, link)
83✔
2503
        }
83✔
2504

2505
        return channelLinks, nil
79✔
2506
}
2507

2508
// CircuitModifier returns a reference to subset of the interfaces provided by
2509
// the circuit map, to allow links to open and close circuits.
2510
func (s *Switch) CircuitModifier() CircuitModifier {
218✔
2511
        return s.circuits
218✔
2512
}
218✔
2513

2514
// CircuitLookup returns a reference to subset of the interfaces provided by the
2515
// circuit map, to allow looking up circuits.
2516
func (s *Switch) CircuitLookup() CircuitLookup {
3✔
2517
        return s.circuits
3✔
2518
}
3✔
2519

2520
// commitCircuits persistently adds a circuit to the switch's circuit map.
2521
func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
2522
        *CircuitFwdActions, error) {
17✔
2523

17✔
2524
        return s.circuits.CommitCircuits(circuits...)
17✔
2525
}
17✔
2526

2527
// FlushForwardingEvents flushes out the set of pending forwarding events to
2528
// the persistent log. This will be used by the switch to periodically flush
2529
// out the set of forwarding events to disk. External callers can also use this
2530
// method to ensure all data is flushed to dis before querying the log.
2531
func (s *Switch) FlushForwardingEvents() error {
212✔
2532
        // First, we'll obtain a copy of the current set of pending forwarding
212✔
2533
        // events.
212✔
2534
        s.fwdEventMtx.Lock()
212✔
2535

212✔
2536
        // If we won't have any forwarding events, then we can exit early.
212✔
2537
        if len(s.pendingFwdingEvents) == 0 {
407✔
2538
                s.fwdEventMtx.Unlock()
195✔
2539
                return nil
195✔
2540
        }
195✔
2541

2542
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
20✔
2543
        copy(events[:], s.pendingFwdingEvents[:])
20✔
2544

20✔
2545
        // With the copy obtained, we can now clear out the header pointer of
20✔
2546
        // the current slice. This way, we can re-use the underlying storage
20✔
2547
        // allocated for the slice.
20✔
2548
        s.pendingFwdingEvents = s.pendingFwdingEvents[:0]
20✔
2549
        s.fwdEventMtx.Unlock()
20✔
2550

20✔
2551
        // Finally, we'll write out the copied events to the persistent
20✔
2552
        // forwarding log.
20✔
2553
        return s.cfg.FwdingLog.AddForwardingEvents(events)
20✔
2554
}
2555

2556
// BestHeight returns the best height known to the switch.
2557
func (s *Switch) BestHeight() uint32 {
450✔
2558
        return atomic.LoadUint32(&s.bestHeight)
450✔
2559
}
450✔
2560

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

535✔
2572
        // Retrieve the link's current commitment feerate and dustClosure.
535✔
2573
        feeRate := link.getFeeRate()
535✔
2574
        isDust := link.getDustClosure()
535✔
2575

535✔
2576
        // Evaluate if the HTLC is dust on either sides' commitment.
535✔
2577
        isLocalDust := isDust(
535✔
2578
                feeRate, incoming, lntypes.Local, amount.ToSatoshis(),
535✔
2579
        )
535✔
2580
        isRemoteDust := isDust(
535✔
2581
                feeRate, incoming, lntypes.Remote, amount.ToSatoshis(),
535✔
2582
        )
535✔
2583

535✔
2584
        if !(isLocalDust || isRemoteDust) {
670✔
2585
                // If the HTLC is not dust on either commitment, it's fine to
135✔
2586
                // forward.
135✔
2587
                return false
135✔
2588
        }
135✔
2589

2590
        // Fetch the dust sums currently in the mailbox for this link.
2591
        cid := link.ChanID()
403✔
2592
        sid := link.ShortChanID()
403✔
2593
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
403✔
2594
        localMailDust, remoteMailDust := mailbox.DustPackets()
403✔
2595

403✔
2596
        // If the htlc is dust on the local commitment, we'll obtain the dust
403✔
2597
        // sum for it.
403✔
2598
        if isLocalDust {
806✔
2599
                localSum := link.getDustSum(
403✔
2600
                        lntypes.Local, fn.None[chainfee.SatPerKWeight](),
403✔
2601
                )
403✔
2602
                localSum += localMailDust
403✔
2603

403✔
2604
                // Optionally include the HTLC amount only for outgoing
403✔
2605
                // HTLCs.
403✔
2606
                if !incoming {
766✔
2607
                        localSum += amount
363✔
2608
                }
363✔
2609

2610
                // Finally check against the defined fee threshold.
2611
                if localSum > s.cfg.MaxFeeExposure {
405✔
2612
                        return true
2✔
2613
                }
2✔
2614
        }
2615

2616
        // Also check if the htlc is dust on the remote commitment, if we've
2617
        // reached this point.
2618
        if isRemoteDust {
802✔
2619
                remoteSum := link.getDustSum(
401✔
2620
                        lntypes.Remote, fn.None[chainfee.SatPerKWeight](),
401✔
2621
                )
401✔
2622
                remoteSum += remoteMailDust
401✔
2623

401✔
2624
                // Optionally include the HTLC amount only for outgoing
401✔
2625
                // HTLCs.
401✔
2626
                if !incoming {
762✔
2627
                        remoteSum += amount
361✔
2628
                }
361✔
2629

2630
                // Finally check against the defined fee threshold.
2631
                if remoteSum > s.cfg.MaxFeeExposure {
401✔
2632
                        return true
×
2633
                }
×
2634
        }
2635

2636
        // If we reached this point, this HTLC is fine to forward.
2637
        return false
401✔
2638
}
2639

2640
// failMailboxUpdate is passed to the mailbox orchestrator which in turn passes
2641
// it to individual mailboxes. It allows the mailboxes to construct a
2642
// FailureMessage when failing back HTLC's due to expiry and may include an
2643
// alias in the ShortChannelID field. The outgoingScid is the SCID originally
2644
// used in the onion. The mailboxScid is the SCID that the mailbox and link
2645
// use. The mailboxScid is only used in the non-alias case, so it is always
2646
// the confirmed SCID.
2647
func (s *Switch) failMailboxUpdate(outgoingScid,
2648
        mailboxScid lnwire.ShortChannelID) lnwire.FailureMessage {
14✔
2649

14✔
2650
        // Try to use the failAliasUpdate function in case this is a channel
14✔
2651
        // that uses aliases. If it returns nil, we'll fallback to the original
14✔
2652
        // pre-alias behavior.
14✔
2653
        update := s.failAliasUpdate(outgoingScid, false)
14✔
2654
        if update == nil {
22✔
2655
                // Execute the fallback behavior.
8✔
2656
                var err error
8✔
2657
                update, err = s.cfg.FetchLastChannelUpdate(mailboxScid)
8✔
2658
                if err != nil {
8✔
2659
                        return &lnwire.FailTemporaryNodeFailure{}
×
2660
                }
×
2661
        }
2662

2663
        return lnwire.NewTemporaryChannelFailure(update)
14✔
2664
}
2665

2666
// failAliasUpdate prepares a ChannelUpdate for a failed incoming or outgoing
2667
// HTLC on a channel where the option-scid-alias feature bit was negotiated. If
2668
// the associated channel is not one of these, this function will return nil
2669
// and the caller is expected to handle this properly. In this case, a return
2670
// to the original non-alias behavior is expected.
2671
func (s *Switch) failAliasUpdate(scid lnwire.ShortChannelID,
2672
        incoming bool) *lnwire.ChannelUpdate1 {
37✔
2673

37✔
2674
        // This function does not defer the unlocking because of the database
37✔
2675
        // lookups for ChannelUpdate.
37✔
2676
        s.indexMtx.RLock()
37✔
2677

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

2695
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2696
                        if err != nil {
×
2697
                                return nil
×
2698
                        }
×
2699

2700
                        // Replace the baseScid with the passed-in alias.
2701
                        update.ShortChannelID = scid
×
2702
                        sig, err := s.cfg.SignAliasUpdate(update)
×
2703
                        if err != nil {
×
2704
                                return nil
×
2705
                        }
×
2706

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

2712
                        return update
×
2713
                }
2714

2715
                s.indexMtx.RUnlock()
14✔
2716

14✔
2717
                // Fetch the SCID via the confirmed SCID and replace it with
14✔
2718
                // the alias.
14✔
2719
                update, err := s.cfg.FetchLastChannelUpdate(realScid)
14✔
2720
                if err != nil {
17✔
2721
                        return nil
3✔
2722
                }
3✔
2723

2724
                // In the incoming case, we want to ensure that we don't leak
2725
                // the UTXO in case the channel is private. In the outgoing
2726
                // case, since the alias was used, we do the same thing.
2727
                update.ShortChannelID = scid
14✔
2728
                sig, err := s.cfg.SignAliasUpdate(update)
14✔
2729
                if err != nil {
14✔
2730
                        return nil
×
2731
                }
×
2732

2733
                update.Signature, err = lnwire.NewSigFromSignature(sig)
14✔
2734
                if err != nil {
14✔
2735
                        return nil
×
2736
                }
×
2737

2738
                return update
14✔
2739
        }
2740

2741
        // If the confirmed SCID is not in baseIndex, this is not an
2742
        // option-scid-alias or zero-conf channel.
2743
        baseScid, ok := s.baseIndex[scid]
26✔
2744
        if !ok {
47✔
2745
                s.indexMtx.RUnlock()
21✔
2746
                return nil
21✔
2747
        }
21✔
2748

2749
        // Fetch the link so we can get an alias to use in the ShortChannelID
2750
        // of the ChannelUpdate.
2751
        link, ok := s.forwardingIndex[baseScid]
5✔
2752
        s.indexMtx.RUnlock()
5✔
2753
        if !ok {
5✔
2754
                // This should never happen, but if it does for some reason,
×
2755
                // fallback to the old behavior.
×
2756
                return nil
×
2757
        }
×
2758

2759
        aliases := link.getAliases()
5✔
2760
        if len(aliases) == 0 {
5✔
2761
                // This should never happen, but if it does, fallback.
×
2762
                return nil
×
2763
        }
×
2764

2765
        // Fetch the ChannelUpdate via the real, confirmed SCID.
2766
        update, err := s.cfg.FetchLastChannelUpdate(scid)
5✔
2767
        if err != nil {
5✔
2768
                return nil
×
2769
        }
×
2770

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

2788
                update.Signature, err = lnwire.NewSigFromSignature(sig)
2✔
2789
                if err != nil {
2✔
2790
                        return nil
×
2791
                }
×
2792
        }
2793

2794
        return update
5✔
2795
}
2796

2797
// AddAliasForLink instructs the Switch to update its in-memory maps to reflect
2798
// that a link has a new alias.
2799
func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
2800
        alias lnwire.ShortChannelID) error {
×
2801

×
2802
        // Fetch the link so that we can update the underlying channel's set of
×
2803
        // aliases.
×
2804
        s.indexMtx.RLock()
×
2805
        link, err := s.getLink(chanID)
×
2806
        s.indexMtx.RUnlock()
×
2807
        if err != nil {
×
2808
                return err
×
2809
        }
×
2810

2811
        // If the link is a channel where the option-scid-alias feature bit was
2812
        // not negotiated, we'll return an error.
2813
        if !link.negotiatedAliasFeature() {
×
2814
                return fmt.Errorf("attempted to update non-alias channel")
×
2815
        }
×
2816

2817
        linkScid := link.ShortChanID()
×
2818

×
2819
        // We'll update the maps so the Switch includes this alias in its
×
2820
        // forwarding decisions.
×
2821
        if link.isZeroConf() {
×
2822
                if link.zeroConfConfirmed() {
×
2823
                        // If the channel has confirmed on-chain, we'll
×
2824
                        // add this alias to the aliasToReal map.
×
2825
                        confirmedScid := link.confirmedScid()
×
2826

×
2827
                        s.aliasToReal[alias] = confirmedScid
×
2828
                }
×
2829

2830
                // Add this alias to the baseIndex mapping.
2831
                s.baseIndex[alias] = linkScid
×
2832
        } else if link.negotiatedAliasFeature() {
×
2833
                // The channel is confirmed, so we'll populate the aliasToReal
×
2834
                // and baseIndex maps.
×
2835
                s.aliasToReal[alias] = linkScid
×
2836
                s.baseIndex[alias] = linkScid
×
2837
        }
×
2838

2839
        return nil
×
2840
}
2841

2842
// handlePacketAdd handles forwarding an Add packet.
2843
func (s *Switch) handlePacketAdd(packet *htlcPacket,
2844
        htlc *lnwire.UpdateAddHTLC) error {
85✔
2845

85✔
2846
        // Check if the node is set to reject all onward HTLCs and also make
85✔
2847
        // sure that HTLC is not from the source node.
85✔
2848
        if s.cfg.RejectHTLC {
89✔
2849
                failure := NewDetailedLinkError(
4✔
2850
                        &lnwire.FailChannelDisabled{},
4✔
2851
                        OutgoingFailureForwardsDisabled,
4✔
2852
                )
4✔
2853

4✔
2854
                return s.failAddPacket(packet, failure)
4✔
2855
        }
4✔
2856

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

2873
        s.indexMtx.RLock()
83✔
2874
        targetLink, err := s.getLinkByMapping(packet)
83✔
2875
        if err != nil {
90✔
2876
                s.indexMtx.RUnlock()
7✔
2877

7✔
2878
                log.Debugf("unable to find link with "+
7✔
2879
                        "destination %v", packet.outgoingChanID)
7✔
2880

7✔
2881
                // If packet was forwarded from another channel link than we
7✔
2882
                // should notify this link that some error occurred.
7✔
2883
                linkError := NewLinkError(
7✔
2884
                        &lnwire.FailUnknownNextPeer{},
7✔
2885
                )
7✔
2886

7✔
2887
                return s.failAddPacket(packet, linkError)
7✔
2888
        }
7✔
2889
        targetPeerKey := targetLink.PeerPubKey()
79✔
2890
        interfaceLinks, _ := s.getLinks(targetPeerKey)
79✔
2891
        s.indexMtx.RUnlock()
79✔
2892

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

79✔
2899
        // Find all destination channel links with appropriate bandwidth.
79✔
2900
        var destinations []ChannelLink
79✔
2901
        for _, link := range interfaceLinks {
162✔
2902
                var failure *LinkError
83✔
2903

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

2924
                // If this link can forward the htlc, add it to the set of
2925
                // destinations.
2926
                if failure == nil {
146✔
2927
                        destinations = append(destinations, link)
63✔
2928
                        continue
63✔
2929
                }
2930

2931
                linkErrs[link.ShortChanID()] = failure
23✔
2932
        }
2933

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

2955
                log.Tracef("incoming HTLC(%x) violated "+
19✔
2956
                        "target outgoing link (id=%v) policy: %v",
19✔
2957
                        htlc.PaymentHash[:], packet.outgoingChanID,
19✔
2958
                        linkErr)
19✔
2959

19✔
2960
                return s.failAddPacket(packet, linkErr)
19✔
2961
        }
2962

2963
        // Choose a random link out of the set of links that can forward this
2964
        // htlc. The reason for randomization is to evenly distribute the htlc
2965
        // load without making assumptions about what the best channel is.
2966
        //nolint:gosec
2967
        destination := destinations[rand.Intn(len(destinations))]
63✔
2968

63✔
2969
        // Retrieve the incoming link by its ShortChannelID. Note that the
63✔
2970
        // incomingChanID is never set to hop.Source here.
63✔
2971
        s.indexMtx.RLock()
63✔
2972
        incomingLink, err := s.getLinkByShortID(packet.incomingChanID)
63✔
2973
        s.indexMtx.RUnlock()
63✔
2974
        if err != nil {
63✔
2975
                // If we couldn't find the incoming link, we can't evaluate the
×
2976
                // incoming's exposure to dust, so we just fail the HTLC back.
×
2977
                linkErr := NewLinkError(
×
2978
                        &lnwire.FailTemporaryChannelFailure{},
×
2979
                )
×
2980

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

2984
        // Evaluate whether this HTLC would increase our fee exposure over the
2985
        // threshold on the incoming link. If it does, fail it backwards.
2986
        if s.dustExceedsFeeThreshold(
63✔
2987
                incomingLink, packet.incomingAmount, true,
63✔
2988
        ) {
63✔
2989
                // The incoming dust exceeds the threshold, so we fail the add
×
2990
                // back.
×
2991
                linkErr := NewLinkError(
×
2992
                        &lnwire.FailTemporaryChannelFailure{},
×
2993
                )
×
2994

×
2995
                return s.failAddPacket(packet, linkErr)
×
2996
        }
×
2997

2998
        // Also evaluate whether this HTLC would increase our fee exposure over
2999
        // the threshold on the destination link. If it does, fail it back.
3000
        if s.dustExceedsFeeThreshold(
63✔
3001
                destination, packet.amount, false,
63✔
3002
        ) {
64✔
3003
                // The outgoing dust exceeds the threshold, so we fail the add
1✔
3004
                // back.
1✔
3005
                linkErr := NewLinkError(
1✔
3006
                        &lnwire.FailTemporaryChannelFailure{},
1✔
3007
                )
1✔
3008

1✔
3009
                return s.failAddPacket(packet, linkErr)
1✔
3010
        }
1✔
3011

3012
        // Send the packet to the destination channel link which manages the
3013
        // channel.
3014
        packet.outgoingChanID = destination.ShortChanID()
62✔
3015

62✔
3016
        return destination.handleSwitchPacket(packet)
62✔
3017
}
3018

3019
// handlePacketSettle handles forwarding a settle packet.
3020
func (s *Switch) handlePacketSettle(packet *htlcPacket) error {
403✔
3021
        // If the source of this packet has not been set, use the circuit map
403✔
3022
        // to lookup the origin.
403✔
3023
        circuit, err := s.closeCircuit(packet)
403✔
3024

403✔
3025
        // If the circuit is in the process of closing, we will return a nil as
403✔
3026
        // there's another packet handling undergoing.
403✔
3027
        if errors.Is(err, ErrCircuitClosing) {
406✔
3028
                log.Debugf("Circuit is closing for packet=%v", packet)
3✔
3029
                return nil
3✔
3030
        }
3✔
3031

3032
        // Exit early if there's another error.
3033
        if err != nil {
403✔
3034
                return err
×
3035
        }
×
3036

3037
        // closeCircuit returns a nil circuit when a settle packet returns an
3038
        // ErrUnknownCircuit error upon the inner call to CloseCircuit.
3039
        //
3040
        // NOTE: We can only get a nil circuit when it has already been deleted
3041
        // and when `UpdateFulfillHTLC` is received. After which `RevokeAndAck`
3042
        // is received, which invokes `processRemoteSettleFails` in its link.
3043
        if circuit == nil {
597✔
3044
                log.Debugf("Circuit already closed for packet=%v", packet)
194✔
3045
                return nil
194✔
3046
        }
194✔
3047

3048
        localHTLC := packet.incomingChanID == hop.Source
212✔
3049

212✔
3050
        // If this is a locally initiated HTLC, we need to handle the packet by
212✔
3051
        // storing the network result.
212✔
3052
        //
212✔
3053
        // A blank IncomingChanID in a circuit indicates that it is a pending
212✔
3054
        // user-initiated payment.
212✔
3055
        //
212✔
3056
        // NOTE: `closeCircuit` modifies the state of `packet`.
212✔
3057
        if localHTLC {
395✔
3058
                // TODO(yy): remove the goroutine and send back the error here.
183✔
3059
                s.wg.Add(1)
183✔
3060
                go s.handleLocalResponse(packet)
183✔
3061

183✔
3062
                // If this is a locally initiated HTLC, there's no need to
183✔
3063
                // forward it so we exit.
183✔
3064
                return nil
183✔
3065
        }
183✔
3066

3067
        // If this is an HTLC settle, and it wasn't from a locally initiated
3068
        // HTLC, then we'll log a forwarding event so we can flush it to disk
3069
        // later.
3070
        if circuit.Outgoing != nil {
64✔
3071
                log.Infof("Forwarded HTLC(%x) of %v (fee: %v) "+
32✔
3072
                        "from IncomingChanID(%v) to OutgoingChanID(%v)",
32✔
3073
                        circuit.PaymentHash[:], circuit.OutgoingAmount,
32✔
3074
                        circuit.IncomingAmount-circuit.OutgoingAmount,
32✔
3075
                        circuit.Incoming.ChanID, circuit.Outgoing.ChanID)
32✔
3076

32✔
3077
                s.fwdEventMtx.Lock()
32✔
3078
                s.pendingFwdingEvents = append(
32✔
3079
                        s.pendingFwdingEvents,
32✔
3080
                        channeldb.ForwardingEvent{
32✔
3081
                                Timestamp:      time.Now(),
32✔
3082
                                IncomingChanID: circuit.Incoming.ChanID,
32✔
3083
                                OutgoingChanID: circuit.Outgoing.ChanID,
32✔
3084
                                AmtIn:          circuit.IncomingAmount,
32✔
3085
                                AmtOut:         circuit.OutgoingAmount,
32✔
3086
                                IncomingHtlcID: fn.Some(
32✔
3087
                                        circuit.Incoming.HtlcID,
32✔
3088
                                ),
32✔
3089
                                OutgoingHtlcID: fn.Some(
32✔
3090
                                        circuit.Outgoing.HtlcID,
32✔
3091
                                ),
32✔
3092
                        },
32✔
3093
                )
32✔
3094
                s.fwdEventMtx.Unlock()
32✔
3095
        }
32✔
3096

3097
        // Deliver this packet.
3098
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
32✔
3099
}
3100

3101
// handlePacketFail handles forwarding a fail packet.
3102
func (s *Switch) handlePacketFail(packet *htlcPacket,
3103
        htlc *lnwire.UpdateFailHTLC) error {
141✔
3104

141✔
3105
        // If the source of this packet has not been set, use the circuit map
141✔
3106
        // to lookup the origin.
141✔
3107
        circuit, err := s.closeCircuit(packet)
141✔
3108
        if err != nil {
141✔
3109
                return err
×
3110
        }
×
3111

3112
        // If this is a locally initiated HTLC, we need to handle the packet by
3113
        // storing the network result.
3114
        //
3115
        // A blank IncomingChanID in a circuit indicates that it is a pending
3116
        // user-initiated payment.
3117
        //
3118
        // NOTE: `closeCircuit` modifies the state of `packet`.
3119
        if packet.incomingChanID == hop.Source {
268✔
3120
                // TODO(yy): remove the goroutine and send back the error here.
127✔
3121
                s.wg.Add(1)
127✔
3122
                go s.handleLocalResponse(packet)
127✔
3123

127✔
3124
                // If this is a locally initiated HTLC, there's no need to
127✔
3125
                // forward it so we exit.
127✔
3126
                return nil
127✔
3127
        }
127✔
3128

3129
        // Exit early if this hasSource is true. This flag is only set via
3130
        // mailbox's `FailAdd`. This method has two callsites,
3131
        // - the packet has timed out after `MailboxDeliveryTimeout`, defaults
3132
        //   to 1 min.
3133
        // - the HTLC fails the validation in `channel.AddHTLC`.
3134
        // In either case, the `Reason` field is populated. Thus there's no
3135
        // need to proceed and extract the failure reason below.
3136
        if packet.hasSource {
24✔
3137
                // Deliver this packet.
7✔
3138
                return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
7✔
3139
        }
7✔
3140

3141
        // HTLC resolutions and messages restored from disk don't have the
3142
        // obfuscator set from the original htlc add packet - set it here for
3143
        // use in blinded errors.
3144
        packet.obfuscator = circuit.ErrorEncrypter
10✔
3145

10✔
3146
        switch {
10✔
3147
        // No message to encrypt, locally sourced payment.
3148
        case circuit.ErrorEncrypter == nil:
×
3149
                // TODO(yy) further check this case as we shouldn't end up here
3150
                // as `isLocal` is already false.
3151

3152
        // If this is a resolution message, then we'll need to encrypt it as
3153
        // it's actually internally sourced.
3154
        case packet.isResolution:
3✔
3155
                var err error
3✔
3156
                // TODO(roasbeef): don't need to pass actually?
3✔
3157
                failure := &lnwire.FailPermanentChannelFailure{}
3✔
3158
                htlc.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
3✔
3159
                        failure,
3✔
3160
                )
3✔
3161
                if err != nil {
3✔
3162
                        err = fmt.Errorf("unable to obfuscate error: %w", err)
×
3163
                        log.Error(err)
×
3164
                }
×
3165

3166
        // Alternatively, if the remote party sends us an
3167
        // UpdateFailMalformedHTLC, then we'll need to convert this into a
3168
        // proper well formatted onion error as there's no HMAC currently.
3169
        case packet.convertedError:
5✔
3170
                log.Infof("Converting malformed HTLC error for circuit for "+
5✔
3171
                        "Circuit(%x: (%s, %d) <-> (%s, %d))",
5✔
3172
                        packet.circuit.PaymentHash,
5✔
3173
                        packet.incomingChanID, packet.incomingHTLCID,
5✔
3174
                        packet.outgoingChanID, packet.outgoingHTLCID)
5✔
3175

5✔
3176
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
5✔
3177
                        htlc.Reason,
5✔
3178
                )
5✔
3179

3180
        default:
8✔
3181
                // Otherwise, it's a forwarded error, so we'll perform a
8✔
3182
                // wrapper encryption as normal.
8✔
3183
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
8✔
3184
                        htlc.Reason,
8✔
3185
                )
8✔
3186
        }
3187

3188
        // Deliver this packet.
3189
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
10✔
3190
}
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