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

lightningnetwork / lnd / 16134013004

08 Jul 2025 04:31AM UTC coverage: 57.764% (-0.02%) from 57.787%
16134013004

Pull #10049

github

web-flow
Merge 149221dc3 into b815109b8
Pull Request #10049: multi: prevent duplicates for locally dispatched HTLC attempts

79 of 113 new or added lines in 4 files covered. (69.91%)

142 existing lines in 11 files now uncovered.

98480 of 170488 relevant lines covered (57.76%)

1.79 hits per line

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

72.89
/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
        // attemptStore 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
        attemptStore AttemptStore
265

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
        errChan chan error
412
}
413

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

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

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

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

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

451
        return false, nil
3✔
452
}
453

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

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

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

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

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

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

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

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

533
        return resultChan, nil
3✔
534
}
535

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

544
// SendHTLC attempts to forward an HTLC to the given first hop using the
545
// specified attempt ID. This is used by other subsystems to dispatch
546
// a payment attempt.
547
//
548
// The Switch guarantees that only one HTLC will be forwarded for a given
549
// attemptID, and will return ErrDuplicateAdd for subsequent uses until the ID
550
// is explicitly cleaned from the underlying attempt store.
551
//
552
// This method is safe to call from remote clients (via SendOnion) or by local
553
// subsystems such as the ChannelRouter.
554
func (s *Switch) SendHTLC(firstHop lnwire.ShortChannelID, attemptID uint64,
555
        htlc *lnwire.UpdateAddHTLC) error {
3✔
556

3✔
557
        // Safety check to ensure that this attempt ID is not currently created
3✔
558
        // within the result store.
3✔
559
        err := s.attemptStore.InitAttempt(attemptID)
3✔
560
        if err != nil {
3✔
NEW
561
                if errors.Is(err, ErrPaymentIDAlreadyExists) {
×
NEW
562
                        log.Debugf("Attempt id=%v already exists", attemptID)
×
NEW
563

×
NEW
564
                        return ErrDuplicateAdd
×
NEW
565
                }
×
566

NEW
567
                log.Errorf("unable to initialize attempt id=%d: %v",
×
NEW
568
                        attemptID, err)
×
NEW
569

×
NEW
570
                return err
×
571
        }
572

573
        // Generate and send new update packet, if error will be received on
574
        // this stage it means that packet haven't left boundaries of our
575
        // system and something wrong happened.
576
        packet := &htlcPacket{
3✔
577
                incomingChanID: hop.Source,
3✔
578
                incomingHTLCID: attemptID,
3✔
579
                outgoingChanID: firstHop,
3✔
580
                htlc:           htlc,
3✔
581
                amount:         htlc.Amount,
3✔
582
        }
3✔
583

3✔
584
        // Attempt to fetch the target link before creating a circuit so that
3✔
585
        // we don't leave dangling circuits. The getLocalLink method does not
3✔
586
        // require the circuit variable to be set on the *htlcPacket.
3✔
587
        link, linkErr := s.getLocalLink(packet, htlc)
3✔
588
        if linkErr != nil {
6✔
589
                // Notify the htlc notifier of a link failure on our outgoing
3✔
590
                // link. Incoming timelock/amount values are not set because
3✔
591
                // they are not present for local sends.
3✔
592
                s.cfg.HtlcNotifier.NotifyLinkFailEvent(
3✔
593
                        newHtlcKey(packet),
3✔
594
                        HtlcInfo{
3✔
595
                                OutgoingTimeLock: htlc.Expiry,
3✔
596
                                OutgoingAmt:      htlc.Amount,
3✔
597
                        },
3✔
598
                        HtlcEventTypeSend,
3✔
599
                        linkErr,
3✔
600
                        false,
3✔
601
                )
3✔
602

3✔
603
                return linkErr
3✔
604
        }
3✔
605

606
        // Evaluate whether this HTLC would bypass our fee exposure. If it
607
        // does, don't send it out and instead return an error.
608
        if s.dustExceedsFeeThreshold(link, htlc.Amount, false) {
3✔
609
                // Notify the htlc notifier of a link failure on our outgoing
×
610
                // link. We use the FailTemporaryChannelFailure in place of a
×
611
                // more descriptive error message.
×
612
                linkErr := NewLinkError(
×
613
                        &lnwire.FailTemporaryChannelFailure{},
×
614
                )
×
615
                s.cfg.HtlcNotifier.NotifyLinkFailEvent(
×
616
                        newHtlcKey(packet),
×
617
                        HtlcInfo{
×
618
                                OutgoingTimeLock: htlc.Expiry,
×
619
                                OutgoingAmt:      htlc.Amount,
×
620
                        },
×
621
                        HtlcEventTypeSend,
×
622
                        linkErr,
×
623
                        false,
×
624
                )
×
625

×
626
                return errFeeExposureExceeded
×
627
        }
×
628

629
        circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
3✔
630
        actions, err := s.circuits.CommitCircuits(circuit)
3✔
631
        if err != nil {
3✔
632
                log.Errorf("unable to commit circuit in switch: %v", err)
×
633
                return err
×
634
        }
×
635

636
        // Drop duplicate packet if it has already been seen.
637
        switch {
3✔
638
        case len(actions.Drops) == 1:
×
639
                return ErrDuplicateAdd
×
640

641
        case len(actions.Fails) == 1:
×
642
                return ErrLocalAddFailed
×
643
        }
644

645
        // Give the packet to the link's mailbox so that HTLC's are properly
646
        // canceled back if the mailbox timeout elapses.
647
        packet.circuit = circuit
3✔
648

3✔
649
        return link.handleSwitchPacket(packet)
3✔
650
}
651

652
// UpdateForwardingPolicies sends a message to the switch to update the
653
// forwarding policies for the set of target channels, keyed in chanPolicies.
654
//
655
// NOTE: This function is synchronous and will block until either the
656
// forwarding policies for all links have been updated, or the switch shuts
657
// down.
658
func (s *Switch) UpdateForwardingPolicies(
659
        chanPolicies map[wire.OutPoint]models.ForwardingPolicy) {
3✔
660

3✔
661
        log.Tracef("Updating link policies: %v", lnutils.SpewLogClosure(
3✔
662
                chanPolicies))
3✔
663

3✔
664
        s.indexMtx.RLock()
3✔
665

3✔
666
        // Update each link in chanPolicies.
3✔
667
        for targetLink, policy := range chanPolicies {
6✔
668
                cid := lnwire.NewChanIDFromOutPoint(targetLink)
3✔
669

3✔
670
                link, ok := s.linkIndex[cid]
3✔
671
                if !ok {
3✔
672
                        log.Debugf("Unable to find ChannelPoint(%v) to update "+
×
673
                                "link policy", targetLink)
×
674
                        continue
×
675
                }
676

677
                link.UpdateForwardingPolicy(policy)
3✔
678
        }
679

680
        s.indexMtx.RUnlock()
3✔
681
}
682

683
// IsForwardedHTLC checks for a given channel and htlc index if it is related
684
// to an opened circuit that represents a forwarded payment.
685
func (s *Switch) IsForwardedHTLC(chanID lnwire.ShortChannelID,
686
        htlcIndex uint64) bool {
3✔
687

3✔
688
        circuit := s.circuits.LookupOpenCircuit(models.CircuitKey{
3✔
689
                ChanID: chanID,
3✔
690
                HtlcID: htlcIndex,
3✔
691
        })
3✔
692
        return circuit != nil && circuit.Incoming.ChanID != hop.Source
3✔
693
}
3✔
694

695
// ForwardPackets adds a list of packets to the switch for processing. Fails
696
// and settles are added on a first past, simultaneously constructing circuits
697
// for any adds. After persisting the circuits, another pass of the adds is
698
// given to forward them through the router. The sending link's quit channel is
699
// used to prevent deadlocks when the switch stops a link in the midst of
700
// forwarding.
701
func (s *Switch) ForwardPackets(linkQuit <-chan struct{},
702
        packets ...*htlcPacket) error {
3✔
703

3✔
704
        var (
3✔
705
                // fwdChan is a buffered channel used to receive err msgs from
3✔
706
                // the htlcPlex when forwarding this batch.
3✔
707
                fwdChan = make(chan error, len(packets))
3✔
708

3✔
709
                // numSent keeps a running count of how many packets are
3✔
710
                // forwarded to the switch, which determines how many responses
3✔
711
                // we will wait for on the fwdChan..
3✔
712
                numSent int
3✔
713
        )
3✔
714

3✔
715
        // No packets, nothing to do.
3✔
716
        if len(packets) == 0 {
6✔
717
                return nil
3✔
718
        }
3✔
719

720
        // Setup a barrier to prevent the background tasks from processing
721
        // responses until this function returns to the user.
722
        var wg sync.WaitGroup
3✔
723
        wg.Add(1)
3✔
724
        defer wg.Done()
3✔
725

3✔
726
        // Before spawning the following goroutine to proxy our error responses,
3✔
727
        // check to see if we have already been issued a shutdown request. If
3✔
728
        // so, we exit early to avoid incrementing the switch's waitgroup while
3✔
729
        // it is already in the process of shutting down.
3✔
730
        select {
3✔
UNCOV
731
        case <-linkQuit:
×
UNCOV
732
                return nil
×
733
        case <-s.quit:
×
734
                return nil
×
735
        default:
3✔
736
                // Spawn a goroutine to log the errors returned from failed packets.
3✔
737
                s.wg.Add(1)
3✔
738
                go s.logFwdErrs(&numSent, &wg, fwdChan)
3✔
739
        }
740

741
        // Make a first pass over the packets, forwarding any settles or fails.
742
        // As adds are found, we create a circuit and append it to our set of
743
        // circuits to be written to disk.
744
        var circuits []*PaymentCircuit
3✔
745
        var addBatch []*htlcPacket
3✔
746
        for _, packet := range packets {
6✔
747
                switch htlc := packet.htlc.(type) {
3✔
748
                case *lnwire.UpdateAddHTLC:
3✔
749
                        circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
3✔
750
                        packet.circuit = circuit
3✔
751
                        circuits = append(circuits, circuit)
3✔
752
                        addBatch = append(addBatch, packet)
3✔
753
                default:
3✔
754
                        err := s.routeAsync(packet, fwdChan, linkQuit)
3✔
755
                        if err != nil {
3✔
756
                                return fmt.Errorf("failed to forward packet %w",
×
757
                                        err)
×
758
                        }
×
759
                        numSent++
3✔
760
                }
761
        }
762

763
        // If this batch did not contain any circuits to commit, we can return
764
        // early.
765
        if len(circuits) == 0 {
6✔
766
                return nil
3✔
767
        }
3✔
768

769
        // Write any circuits that we found to disk.
770
        actions, err := s.circuits.CommitCircuits(circuits...)
3✔
771
        if err != nil {
3✔
772
                log.Errorf("unable to commit circuits in switch: %v", err)
×
773
        }
×
774

775
        // Split the htlc packets by comparing an in-order seek to the head of
776
        // the added, dropped, or failed circuits.
777
        //
778
        // NOTE: This assumes each list is guaranteed to be a subsequence of the
779
        // circuits, and that the union of the sets results in the original set
780
        // of circuits.
781
        var addedPackets, failedPackets []*htlcPacket
3✔
782
        for _, packet := range addBatch {
6✔
783
                switch {
3✔
784
                case len(actions.Adds) > 0 && packet.circuit == actions.Adds[0]:
3✔
785
                        addedPackets = append(addedPackets, packet)
3✔
786
                        actions.Adds = actions.Adds[1:]
3✔
787

788
                case len(actions.Drops) > 0 && packet.circuit == actions.Drops[0]:
3✔
789
                        actions.Drops = actions.Drops[1:]
3✔
790

791
                case len(actions.Fails) > 0 && packet.circuit == actions.Fails[0]:
×
792
                        failedPackets = append(failedPackets, packet)
×
793
                        actions.Fails = actions.Fails[1:]
×
794
                }
795
        }
796

797
        // Now, forward any packets for circuits that were successfully added to
798
        // the switch's circuit map.
799
        for _, packet := range addedPackets {
6✔
800
                err := s.routeAsync(packet, fwdChan, linkQuit)
3✔
801
                if err != nil {
3✔
802
                        return fmt.Errorf("failed to forward packet %w", err)
×
803
                }
×
804
                numSent++
3✔
805
        }
806

807
        // Lastly, for any packets that failed, this implies that they were
808
        // left in a half added state, which can happen when recovering from
809
        // failures.
810
        if len(failedPackets) > 0 {
3✔
811
                var failure lnwire.FailureMessage
×
812
                incomingID := failedPackets[0].incomingChanID
×
813

×
814
                // If the incoming channel is an option_scid_alias channel,
×
815
                // then we'll need to replace the SCID in the ChannelUpdate.
×
816
                update := s.failAliasUpdate(incomingID, true)
×
817
                if update == nil {
×
818
                        // Fallback to the original non-option behavior.
×
819
                        update, err := s.cfg.FetchLastChannelUpdate(
×
820
                                incomingID,
×
821
                        )
×
822
                        if err != nil {
×
823
                                failure = &lnwire.FailTemporaryNodeFailure{}
×
824
                        } else {
×
825
                                failure = lnwire.NewTemporaryChannelFailure(
×
826
                                        update,
×
827
                                )
×
828
                        }
×
829
                } else {
×
830
                        // This is an option_scid_alias channel.
×
831
                        failure = lnwire.NewTemporaryChannelFailure(update)
×
832
                }
×
833

834
                linkError := NewDetailedLinkError(
×
835
                        failure, OutgoingFailureIncompleteForward,
×
836
                )
×
837

×
838
                for _, packet := range failedPackets {
×
839
                        // We don't handle the error here since this method
×
840
                        // always returns an error.
×
841
                        _ = s.failAddPacket(packet, linkError)
×
842
                }
×
843
        }
844

845
        return nil
3✔
846
}
847

848
// logFwdErrs logs any errors received on `fwdChan`.
849
func (s *Switch) logFwdErrs(num *int, wg *sync.WaitGroup, fwdChan chan error) {
3✔
850
        defer s.wg.Done()
3✔
851

3✔
852
        // Wait here until the outer function has finished persisting
3✔
853
        // and routing the packets. This guarantees we don't read from num until
3✔
854
        // the value is accurate.
3✔
855
        wg.Wait()
3✔
856

3✔
857
        numSent := *num
3✔
858
        for i := 0; i < numSent; i++ {
6✔
859
                select {
3✔
860
                case err := <-fwdChan:
3✔
861
                        if err != nil {
6✔
862
                                log.Errorf("Unhandled error while reforwarding htlc "+
3✔
863
                                        "settle/fail over htlcswitch: %v", err)
3✔
864
                        }
3✔
865
                case <-s.quit:
×
866
                        log.Errorf("unable to forward htlc packet " +
×
867
                                "htlc switch was stopped")
×
868
                        return
×
869
                }
870
        }
871
}
872

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

3✔
881
        command := &plexPacket{
3✔
882
                pkt: packet,
3✔
883
                err: errChan,
3✔
884
        }
3✔
885

3✔
886
        select {
3✔
887
        case s.htlcPlex <- command:
3✔
888
                return nil
3✔
889
        case <-linkQuit:
×
890
                return ErrLinkShuttingDown
×
891
        case <-s.quit:
×
892
                return errors.New("htlc switch was stopped")
×
893
        }
894
}
895

896
// getLocalLink handles the addition of a htlc for a send that originates from
897
// our node. It returns the link that the htlc should be forwarded outwards on,
898
// and a link error if the htlc cannot be forwarded.
899
func (s *Switch) getLocalLink(pkt *htlcPacket, htlc *lnwire.UpdateAddHTLC) (
900
        ChannelLink, *LinkError) {
3✔
901

3✔
902
        // Try to find links by node destination.
3✔
903
        s.indexMtx.RLock()
3✔
904
        link, err := s.getLinkByShortID(pkt.outgoingChanID)
3✔
905
        if err != nil {
6✔
906
                // If the link was not found for the outgoingChanID, an outside
3✔
907
                // subsystem may be using the confirmed SCID of a zero-conf
3✔
908
                // channel. In this case, we'll consult the Switch maps to see
3✔
909
                // if an alias exists and use the alias to lookup the link.
3✔
910
                // This extra step is a consequence of not updating the Switch
3✔
911
                // forwardingIndex when a zero-conf channel is confirmed. We
3✔
912
                // don't need to change the outgoingChanID since the link will
3✔
913
                // do that upon receiving the packet.
3✔
914
                baseScid, ok := s.baseIndex[pkt.outgoingChanID]
3✔
915
                if !ok {
6✔
916
                        s.indexMtx.RUnlock()
3✔
917
                        log.Errorf("Link %v not found", pkt.outgoingChanID)
3✔
918
                        return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
3✔
919
                }
3✔
920

921
                // The base SCID was found, so we'll use that to fetch the
922
                // link.
923
                link, err = s.getLinkByShortID(baseScid)
3✔
924
                if err != nil {
3✔
925
                        s.indexMtx.RUnlock()
×
926
                        log.Errorf("Link %v not found", baseScid)
×
927
                        return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
×
928
                }
×
929
        }
930
        // We finished looking up the indexes, so we can unlock the mutex before
931
        // performing the link operations which might also acquire the lock
932
        // in case e.g. failAliasUpdate is called.
933
        s.indexMtx.RUnlock()
3✔
934

3✔
935
        if !link.EligibleToForward() {
3✔
936
                log.Errorf("Link %v is not available to forward",
×
937
                        pkt.outgoingChanID)
×
938

×
939
                // The update does not need to be populated as the error
×
940
                // will be returned back to the router.
×
941
                return nil, NewDetailedLinkError(
×
942
                        lnwire.NewTemporaryChannelFailure(nil),
×
943
                        OutgoingFailureLinkNotEligible,
×
944
                )
×
945
        }
×
946

947
        // Ensure that the htlc satisfies the outgoing channel policy.
948
        currentHeight := atomic.LoadUint32(&s.bestHeight)
3✔
949
        htlcErr := link.CheckHtlcTransit(
3✔
950
                htlc.PaymentHash, htlc.Amount, htlc.Expiry, currentHeight,
3✔
951
                htlc.CustomRecords,
3✔
952
        )
3✔
953
        if htlcErr != nil {
6✔
954
                log.Errorf("Link %v policy for local forward not "+
3✔
955
                        "satisfied", pkt.outgoingChanID)
3✔
956
                return nil, htlcErr
3✔
957
        }
3✔
958

959
        return link, nil
3✔
960
}
961

962
// handleLocalResponse processes a Settle or Fail responding to a
963
// locally-initiated payment. This is handled asynchronously to avoid blocking
964
// the main event loop within the switch, as these operations can require
965
// multiple db transactions. The guarantees of the circuit map are stringent
966
// enough such that we are able to tolerate reordering of these operations
967
// without side effects. The primary operations handled are:
968
//  1. Save the payment result to the pending payment store.
969
//  2. Notify subscribers about the payment result.
970
//  3. Ack settle/fail references, to avoid resending this response internally
971
//  4. Teardown the closing circuit in the circuit map
972
//
973
// NOTE: This method MUST be spawned as a goroutine.
974
func (s *Switch) handleLocalResponse(pkt *htlcPacket) {
3✔
975
        defer s.wg.Done()
3✔
976

3✔
977
        attemptID := pkt.incomingHTLCID
3✔
978

3✔
979
        // The error reason will be unencypted in case this a local
3✔
980
        // failure or a converted error.
3✔
981
        unencrypted := pkt.localFailure || pkt.convertedError
3✔
982
        n := &networkResult{
3✔
983
                msg:          pkt.htlc,
3✔
984
                unencrypted:  unencrypted,
3✔
985
                isResolution: pkt.isResolution,
3✔
986
        }
3✔
987

3✔
988
        // Store the result to the db. This will also notify subscribers about
3✔
989
        // the result.
3✔
990
        if err := s.attemptStore.StoreResult(attemptID, n); err != nil {
3✔
991
                log.Errorf("Unable to store attempt result for pid=%v: %v",
×
992
                        attemptID, err)
×
993
                return
×
994
        }
×
995

996
        // First, we'll clean up any fwdpkg references, circuit entries, and
997
        // mark in our db that the payment for this payment hash has either
998
        // succeeded or failed.
999
        //
1000
        // If this response is contained in a forwarding package, we'll start by
1001
        // acking the settle/fail so that we don't continue to retransmit the
1002
        // HTLC internally.
1003
        if pkt.destRef != nil {
6✔
1004
                if err := s.ackSettleFail(*pkt.destRef); err != nil {
3✔
1005
                        log.Warnf("Unable to ack settle/fail reference: %s: %v",
×
1006
                                *pkt.destRef, err)
×
1007
                        return
×
1008
                }
×
1009
        }
1010

1011
        // Next, we'll remove the circuit since we are about to complete an
1012
        // fulfill/fail of this HTLC. Since we've already removed the
1013
        // settle/fail fwdpkg reference, the response from the peer cannot be
1014
        // replayed internally if this step fails. If this happens, this logic
1015
        // will be executed when a provided resolution message comes through.
1016
        // This can only happen if the circuit is still open, which is why this
1017
        // ordering is chosen.
1018
        if err := s.teardownCircuit(pkt); err != nil {
3✔
1019
                log.Errorf("Unable to teardown circuit %s: %v",
×
1020
                        pkt.inKey(), err)
×
1021
                return
×
1022
        }
×
1023

1024
        // Finally, notify on the htlc failure or success that has been handled.
1025
        key := newHtlcKey(pkt)
3✔
1026
        eventType := getEventType(pkt)
3✔
1027

3✔
1028
        switch htlc := pkt.htlc.(type) {
3✔
1029
        case *lnwire.UpdateFulfillHTLC:
3✔
1030
                s.cfg.HtlcNotifier.NotifySettleEvent(key, htlc.PaymentPreimage,
3✔
1031
                        eventType)
3✔
1032

1033
        case *lnwire.UpdateFailHTLC:
3✔
1034
                s.cfg.HtlcNotifier.NotifyForwardingFailEvent(key, eventType)
3✔
1035
        }
1036
}
1037

1038
// extractResult uses the given deobfuscator to extract the payment result from
1039
// the given network message.
1040
func (s *Switch) extractResult(deobfuscator ErrorDecrypter, n *networkResult,
1041
        attemptID uint64, paymentHash lntypes.Hash) (*PaymentResult, error) {
3✔
1042

3✔
1043
        switch htlc := n.msg.(type) {
3✔
1044

1045
        // We've received a settle update which means we can finalize the user
1046
        // payment and return successful response.
1047
        case *lnwire.UpdateFulfillHTLC:
3✔
1048
                return &PaymentResult{
3✔
1049
                        Preimage: htlc.PaymentPreimage,
3✔
1050
                }, nil
3✔
1051

1052
        // We've received a fail update which means we can finalize the
1053
        // user payment and return fail response.
1054
        case *lnwire.UpdateFailHTLC:
3✔
1055
                // TODO(yy): construct deobfuscator here to avoid creating it
3✔
1056
                // in paymentLifecycle even for settled HTLCs.
3✔
1057
                paymentErr := s.parseFailedPayment(
3✔
1058
                        deobfuscator, attemptID, paymentHash, n.unencrypted,
3✔
1059
                        n.isResolution, htlc,
3✔
1060
                )
3✔
1061

3✔
1062
                return &PaymentResult{
3✔
1063
                        Error: paymentErr,
3✔
1064
                }, nil
3✔
1065

1066
        default:
×
1067
                return nil, fmt.Errorf("received unknown response type: %T",
×
1068
                        htlc)
×
1069
        }
1070
}
1071

1072
// parseFailedPayment determines the appropriate failure message to return to
1073
// a user initiated payment. The three cases handled are:
1074
//  1. An unencrypted failure, which should already plaintext.
1075
//  2. A resolution from the chain arbitrator, which possibly has no failure
1076
//     reason attached.
1077
//  3. A failure from the remote party, which will need to be decrypted using
1078
//     the payment deobfuscator.
1079
func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
1080
        attemptID uint64, paymentHash lntypes.Hash, unencrypted,
1081
        isResolution bool, htlc *lnwire.UpdateFailHTLC) error {
3✔
1082

3✔
1083
        switch {
3✔
1084

1085
        // The payment never cleared the link, so we don't need to
1086
        // decrypt the error, simply decode it them report back to the
1087
        // user.
UNCOV
1088
        case unencrypted:
×
UNCOV
1089
                r := bytes.NewReader(htlc.Reason)
×
UNCOV
1090
                failureMsg, err := lnwire.DecodeFailure(r, 0)
×
UNCOV
1091
                if err != nil {
×
1092
                        // If we could not decode the failure reason, return a link
×
1093
                        // error indicating that we failed to decode the onion.
×
1094
                        linkError := NewDetailedLinkError(
×
1095
                                // As this didn't even clear the link, we don't
×
1096
                                // need to apply an update here since it goes
×
1097
                                // directly to the router.
×
1098
                                lnwire.NewTemporaryChannelFailure(nil),
×
1099
                                OutgoingFailureDecodeError,
×
1100
                        )
×
1101

×
1102
                        log.Errorf("%v: (hash=%v, pid=%d): %v",
×
1103
                                linkError.FailureDetail.FailureString(),
×
1104
                                paymentHash, attemptID, err)
×
1105

×
1106
                        return linkError
×
1107
                }
×
1108

1109
                // If we successfully decoded the failure reason, return it.
UNCOV
1110
                return NewLinkError(failureMsg)
×
1111

1112
        // A payment had to be timed out on chain before it got past
1113
        // the first hop. In this case, we'll report a permanent
1114
        // channel failure as this means us, or the remote party had to
1115
        // go on chain.
1116
        case isResolution && htlc.Reason == nil:
3✔
1117
                linkError := NewDetailedLinkError(
3✔
1118
                        &lnwire.FailPermanentChannelFailure{},
3✔
1119
                        OutgoingFailureOnChainTimeout,
3✔
1120
                )
3✔
1121

3✔
1122
                log.Infof("%v: hash=%v, pid=%d",
3✔
1123
                        linkError.FailureDetail.FailureString(),
3✔
1124
                        paymentHash, attemptID)
3✔
1125

3✔
1126
                return linkError
3✔
1127

1128
        // A regular multi-hop payment error that we'll need to
1129
        // decrypt.
1130
        default:
3✔
1131
                // We'll attempt to fully decrypt the onion encrypted
3✔
1132
                // error. If we're unable to then we'll bail early.
3✔
1133
                failure, err := deobfuscator.DecryptError(htlc.Reason)
3✔
1134
                if err != nil {
3✔
1135
                        log.Errorf("unable to de-obfuscate onion failure "+
×
1136
                                "(hash=%v, pid=%d): %v",
×
1137
                                paymentHash, attemptID, err)
×
1138

×
1139
                        return ErrUnreadableFailureMessage
×
1140
                }
×
1141

1142
                return failure
3✔
1143
        }
1144
}
1145

1146
// handlePacketForward is used in cases when we need forward the htlc update
1147
// from one channel link to another and be able to propagate the settle/fail
1148
// updates back. This behaviour is achieved by creation of payment circuits.
1149
func (s *Switch) handlePacketForward(packet *htlcPacket) error {
3✔
1150
        switch htlc := packet.htlc.(type) {
3✔
1151
        // Channel link forwarded us a new htlc, therefore we initiate the
1152
        // payment circuit within our internal state so we can properly forward
1153
        // the ultimate settle message back latter.
1154
        case *lnwire.UpdateAddHTLC:
3✔
1155
                return s.handlePacketAdd(packet, htlc)
3✔
1156

1157
        case *lnwire.UpdateFulfillHTLC:
3✔
1158
                return s.handlePacketSettle(packet)
3✔
1159

1160
        // Channel link forwarded us an update_fail_htlc message.
1161
        //
1162
        // NOTE: when the channel link receives an update_fail_malformed_htlc
1163
        // from upstream, it will convert the message into update_fail_htlc and
1164
        // forward it. Thus there's no need to catch `UpdateFailMalformedHTLC`
1165
        // here.
1166
        case *lnwire.UpdateFailHTLC:
3✔
1167
                return s.handlePacketFail(packet, htlc)
3✔
1168

1169
        default:
×
1170
                return fmt.Errorf("wrong update type: %T", htlc)
×
1171
        }
1172
}
1173

1174
// checkCircularForward checks whether a forward is circular (arrives and
1175
// departs on the same link) and returns a link error if the switch is
1176
// configured to disallow this behaviour.
1177
func (s *Switch) checkCircularForward(incoming, outgoing lnwire.ShortChannelID,
1178
        allowCircular bool, paymentHash lntypes.Hash) *LinkError {
3✔
1179

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

3✔
1183
        // If they are equal, we can skip the alias mapping checks.
3✔
1184
        if incoming == outgoing {
3✔
1185
                // The switch may be configured to allow circular routes, so
×
1186
                // just log and return nil.
×
1187
                if allowCircular {
×
1188
                        log.Debugf("allowing circular route over link: %v "+
×
1189
                                "(payment hash: %x)", incoming, paymentHash)
×
1190
                        return nil
×
1191
                }
×
1192

1193
                // Otherwise, we'll return a temporary channel failure.
1194
                return NewDetailedLinkError(
×
1195
                        lnwire.NewTemporaryChannelFailure(nil),
×
1196
                        OutgoingFailureCircularRoute,
×
1197
                )
×
1198
        }
1199

1200
        // We'll fetch the "base" SCID from the baseIndex for the incoming and
1201
        // outgoing SCIDs. If either one does not have a base SCID, then the
1202
        // two channels are not equal since one will be a channel that does not
1203
        // need a mapping and SCID equality was checked above. If the "base"
1204
        // SCIDs are equal, then this is a circular route. Otherwise, it isn't.
1205
        s.indexMtx.RLock()
3✔
1206
        incomingBaseScid, ok := s.baseIndex[incoming]
3✔
1207
        if !ok {
6✔
1208
                // This channel does not use baseIndex, bail out.
3✔
1209
                s.indexMtx.RUnlock()
3✔
1210
                return nil
3✔
1211
        }
3✔
1212

1213
        outgoingBaseScid, ok := s.baseIndex[outgoing]
3✔
1214
        if !ok {
6✔
1215
                // This channel does not use baseIndex, bail out.
3✔
1216
                s.indexMtx.RUnlock()
3✔
1217
                return nil
3✔
1218
        }
3✔
1219
        s.indexMtx.RUnlock()
3✔
1220

3✔
1221
        // Check base SCID equality.
3✔
1222
        if incomingBaseScid != outgoingBaseScid {
6✔
1223
                log.Tracef("Incoming base SCID %v does not match outgoing "+
3✔
1224
                        "base SCID %v (payment hash: %x)", incomingBaseScid,
3✔
1225
                        outgoingBaseScid, paymentHash[:])
3✔
1226

3✔
1227
                // The base SCIDs are not equal so these are not the same
3✔
1228
                // channel.
3✔
1229
                return nil
3✔
1230
        }
3✔
1231

1232
        // If the incoming and outgoing link are equal, the htlc is part of a
1233
        // circular route which may be used to lock up our liquidity. If the
1234
        // switch is configured to allow circular routes, log that we are
1235
        // allowing the route then return nil.
1236
        if allowCircular {
×
1237
                log.Debugf("allowing circular route over link: %v "+
×
1238
                        "(payment hash: %x)", incoming, paymentHash)
×
1239
                return nil
×
1240
        }
×
1241

1242
        // If our node disallows circular routes, return a temporary channel
1243
        // failure. There is nothing wrong with the policy used by the remote
1244
        // node, so we do not include a channel update.
1245
        return NewDetailedLinkError(
×
1246
                lnwire.NewTemporaryChannelFailure(nil),
×
1247
                OutgoingFailureCircularRoute,
×
1248
        )
×
1249
}
1250

1251
// failAddPacket encrypts a fail packet back to an add packet's source.
1252
// The ciphertext will be derived from the failure message proivded by context.
1253
// This method returns the failErr if all other steps complete successfully.
1254
func (s *Switch) failAddPacket(packet *htlcPacket, failure *LinkError) error {
3✔
1255
        // Encrypt the failure so that the sender will be able to read the error
3✔
1256
        // message. Since we failed this packet, we use EncryptFirstHop to
3✔
1257
        // obfuscate the failure for their eyes only.
3✔
1258
        reason, err := packet.obfuscator.EncryptFirstHop(failure.WireMessage())
3✔
1259
        if err != nil {
3✔
1260
                err := fmt.Errorf("unable to obfuscate "+
×
1261
                        "error: %v", err)
×
1262
                log.Error(err)
×
1263
                return err
×
1264
        }
×
1265

1266
        log.Error(failure.Error())
3✔
1267

3✔
1268
        // Create a failure packet for this htlc. The full set of
3✔
1269
        // information about the htlc failure is included so that they can
3✔
1270
        // be included in link failure notifications.
3✔
1271
        failPkt := &htlcPacket{
3✔
1272
                sourceRef:       packet.sourceRef,
3✔
1273
                incomingChanID:  packet.incomingChanID,
3✔
1274
                incomingHTLCID:  packet.incomingHTLCID,
3✔
1275
                outgoingChanID:  packet.outgoingChanID,
3✔
1276
                outgoingHTLCID:  packet.outgoingHTLCID,
3✔
1277
                incomingAmount:  packet.incomingAmount,
3✔
1278
                amount:          packet.amount,
3✔
1279
                incomingTimeout: packet.incomingTimeout,
3✔
1280
                outgoingTimeout: packet.outgoingTimeout,
3✔
1281
                circuit:         packet.circuit,
3✔
1282
                obfuscator:      packet.obfuscator,
3✔
1283
                linkFailure:     failure,
3✔
1284
                htlc: &lnwire.UpdateFailHTLC{
3✔
1285
                        Reason: reason,
3✔
1286
                },
3✔
1287
        }
3✔
1288

3✔
1289
        // Route a fail packet back to the source link.
3✔
1290
        err = s.mailOrchestrator.Deliver(failPkt.incomingChanID, failPkt)
3✔
1291
        if err != nil {
3✔
1292
                err = fmt.Errorf("source chanid=%v unable to "+
×
1293
                        "handle switch packet: %v",
×
1294
                        packet.incomingChanID, err)
×
1295
                log.Error(err)
×
1296
                return err
×
1297
        }
×
1298

1299
        return failure
3✔
1300
}
1301

1302
// closeCircuit accepts a settle or fail htlc and the associated htlc packet and
1303
// attempts to determine the source that forwarded this htlc. This method will
1304
// set the incoming chan and htlc ID of the given packet if the source was
1305
// found, and will properly [re]encrypt any failure messages.
1306
func (s *Switch) closeCircuit(pkt *htlcPacket) (*PaymentCircuit, error) {
3✔
1307
        // If the packet has its source, that means it was failed locally by
3✔
1308
        // the outgoing link. We fail it here to make sure only one response
3✔
1309
        // makes it through the switch.
3✔
1310
        if pkt.hasSource {
3✔
UNCOV
1311
                circuit, err := s.circuits.FailCircuit(pkt.inKey())
×
UNCOV
1312
                switch err {
×
1313

1314
                // Circuit successfully closed.
UNCOV
1315
                case nil:
×
UNCOV
1316
                        return circuit, nil
×
1317

1318
                // Circuit was previously closed, but has not been deleted.
1319
                // We'll just drop this response until the circuit has been
1320
                // fully removed.
1321
                case ErrCircuitClosing:
×
1322
                        return nil, err
×
1323

1324
                // Failed to close circuit because it does not exist. This is
1325
                // likely because the circuit was already successfully closed.
1326
                // Since this packet failed locally, there is no forwarding
1327
                // package entry to acknowledge.
1328
                case ErrUnknownCircuit:
×
1329
                        return nil, err
×
1330

1331
                // Unexpected error.
1332
                default:
×
1333
                        return nil, err
×
1334
                }
1335
        }
1336

1337
        // Otherwise, this is packet was received from the remote party.  Use
1338
        // circuit map to find the incoming link to receive the settle/fail.
1339
        circuit, err := s.circuits.CloseCircuit(pkt.outKey())
3✔
1340
        switch err {
3✔
1341

1342
        // Open circuit successfully closed.
1343
        case nil:
3✔
1344
                pkt.incomingChanID = circuit.Incoming.ChanID
3✔
1345
                pkt.incomingHTLCID = circuit.Incoming.HtlcID
3✔
1346
                pkt.circuit = circuit
3✔
1347
                pkt.sourceRef = &circuit.AddRef
3✔
1348

3✔
1349
                pktType := "SETTLE"
3✔
1350
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
6✔
1351
                        pktType = "FAIL"
3✔
1352
                }
3✔
1353

1354
                log.Debugf("Closed completed %s circuit for %x: "+
3✔
1355
                        "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
3✔
1356
                        pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1357
                        pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1358

3✔
1359
                return circuit, nil
3✔
1360

1361
        // Circuit was previously closed, but has not been deleted. We'll just
1362
        // drop this response until the circuit has been removed.
1363
        case ErrCircuitClosing:
3✔
1364
                return nil, err
3✔
1365

1366
        // Failed to close circuit because it does not exist. This is likely
1367
        // because the circuit was already successfully closed.
1368
        case ErrUnknownCircuit:
3✔
1369
                if pkt.destRef != nil {
6✔
1370
                        // Add this SettleFailRef to the set of pending settle/fail entries
3✔
1371
                        // awaiting acknowledgement.
3✔
1372
                        s.pendingSettleFails = append(s.pendingSettleFails, *pkt.destRef)
3✔
1373
                }
3✔
1374

1375
                // If this is a settle, we will not log an error message as settles
1376
                // are expected to hit the ErrUnknownCircuit case. The only way fails
1377
                // can hit this case if the link restarts after having just sent a fail
1378
                // to the switch.
1379
                _, isSettle := pkt.htlc.(*lnwire.UpdateFulfillHTLC)
3✔
1380
                if !isSettle {
3✔
1381
                        err := fmt.Errorf("unable to find target channel "+
×
1382
                                "for HTLC fail: channel ID = %s, "+
×
1383
                                "HTLC ID = %d", pkt.outgoingChanID,
×
1384
                                pkt.outgoingHTLCID)
×
1385
                        log.Error(err)
×
1386

×
1387
                        return nil, err
×
1388
                }
×
1389

1390
                return nil, nil
3✔
1391

1392
        // Unexpected error.
1393
        default:
×
1394
                return nil, err
×
1395
        }
1396
}
1397

1398
// ackSettleFail is used by the switch to ACK any settle/fail entries in the
1399
// forwarding package of the outgoing link for a payment circuit. We do this if
1400
// we're the originator of the payment, so the link stops attempting to
1401
// re-broadcast.
1402
func (s *Switch) ackSettleFail(settleFailRefs ...channeldb.SettleFailRef) error {
3✔
1403
        return kvdb.Batch(s.cfg.DB, func(tx kvdb.RwTx) error {
6✔
1404
                return s.cfg.SwitchPackager.AckSettleFails(tx, settleFailRefs...)
3✔
1405
        })
3✔
1406
}
1407

1408
// teardownCircuit removes a pending or open circuit from the switch's circuit
1409
// map and prints useful logging statements regarding the outcome.
1410
func (s *Switch) teardownCircuit(pkt *htlcPacket) error {
3✔
1411
        var pktType string
3✔
1412
        switch htlc := pkt.htlc.(type) {
3✔
1413
        case *lnwire.UpdateFulfillHTLC:
3✔
1414
                pktType = "SETTLE"
3✔
1415
        case *lnwire.UpdateFailHTLC:
3✔
1416
                pktType = "FAIL"
3✔
1417
        default:
×
1418
                return fmt.Errorf("cannot tear down packet of type: %T", htlc)
×
1419
        }
1420

1421
        var paymentHash lntypes.Hash
3✔
1422

3✔
1423
        // Perform a defensive check to make sure we don't try to access a nil
3✔
1424
        // circuit.
3✔
1425
        circuit := pkt.circuit
3✔
1426
        if circuit != nil {
6✔
1427
                copy(paymentHash[:], circuit.PaymentHash[:])
3✔
1428
        }
3✔
1429

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

3✔
1433
        err := s.circuits.DeleteCircuits(pkt.inKey())
3✔
1434
        if err != nil {
3✔
1435
                log.Warnf("Failed to tear down circuit (%s, %d) <-> (%s, %d) "+
×
1436
                        "with payment_hash=%v using %s pkt", pkt.incomingChanID,
×
1437
                        pkt.incomingHTLCID, pkt.outgoingChanID,
×
1438
                        pkt.outgoingHTLCID, pkt.circuit.PaymentHash, pktType)
×
1439

×
1440
                return err
×
1441
        }
×
1442

1443
        log.Debugf("Closed %s circuit for %v: (%s, %d) <-> (%s, %d)", pktType,
3✔
1444
                paymentHash, pkt.incomingChanID, pkt.incomingHTLCID,
3✔
1445
                pkt.outgoingChanID, pkt.outgoingHTLCID)
3✔
1446

3✔
1447
        return nil
3✔
1448
}
1449

1450
// CloseLink creates and sends the close channel command to the target link
1451
// directing the specified closure type. If the closure type is CloseRegular,
1452
// targetFeePerKw parameter should be the ideal fee-per-kw that will be used as
1453
// a starting point for close negotiation. The deliveryScript parameter is an
1454
// optional parameter which sets a user specified script to close out to.
1455
func (s *Switch) CloseLink(ctx context.Context, chanPoint *wire.OutPoint,
1456
        closeType contractcourt.ChannelCloseType,
1457
        targetFeePerKw, maxFee chainfee.SatPerKWeight,
1458
        deliveryScript lnwire.DeliveryAddress) (chan interface{}, chan error) {
3✔
1459

3✔
1460
        // TODO(roasbeef) abstract out the close updates.
3✔
1461
        updateChan := make(chan interface{}, 2)
3✔
1462
        errChan := make(chan error, 1)
3✔
1463

3✔
1464
        command := &ChanClose{
3✔
1465
                CloseType:      closeType,
3✔
1466
                ChanPoint:      chanPoint,
3✔
1467
                Updates:        updateChan,
3✔
1468
                TargetFeePerKw: targetFeePerKw,
3✔
1469
                DeliveryScript: deliveryScript,
3✔
1470
                Err:            errChan,
3✔
1471
                MaxFee:         maxFee,
3✔
1472
                Ctx:            ctx,
3✔
1473
        }
3✔
1474

3✔
1475
        select {
3✔
1476
        case s.chanCloseRequests <- command:
3✔
1477
                return updateChan, errChan
3✔
1478

1479
        case <-s.quit:
×
1480
                errChan <- ErrSwitchExiting
×
1481
                close(updateChan)
×
1482
                return updateChan, errChan
×
1483
        }
1484
}
1485

1486
// htlcForwarder is responsible for optimally forwarding (and possibly
1487
// fragmenting) incoming/outgoing HTLCs amongst all active interfaces and their
1488
// links. The duties of the forwarder are similar to that of a network switch,
1489
// in that it facilitates multi-hop payments by acting as a central messaging
1490
// bus. The switch communicates will active links to create, manage, and tear
1491
// down active onion routed payments. Each active channel is modeled as
1492
// networked device with metadata such as the available payment bandwidth, and
1493
// total link capacity.
1494
//
1495
// NOTE: This MUST be run as a goroutine.
1496
func (s *Switch) htlcForwarder() {
3✔
1497
        defer s.wg.Done()
3✔
1498

3✔
1499
        defer func() {
6✔
1500
                s.blockEpochStream.Cancel()
3✔
1501

3✔
1502
                // Remove all links once we've been signalled for shutdown.
3✔
1503
                var linksToStop []ChannelLink
3✔
1504
                s.indexMtx.Lock()
3✔
1505
                for _, link := range s.linkIndex {
6✔
1506
                        activeLink := s.removeLink(link.ChanID())
3✔
1507
                        if activeLink == nil {
3✔
1508
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1509
                                        "on stop", link.ChanID())
×
1510
                                continue
×
1511
                        }
1512
                        linksToStop = append(linksToStop, activeLink)
3✔
1513
                }
1514
                for _, link := range s.pendingLinkIndex {
6✔
1515
                        pendingLink := s.removeLink(link.ChanID())
3✔
1516
                        if pendingLink == nil {
3✔
1517
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1518
                                        "on stop", link.ChanID())
×
1519
                                continue
×
1520
                        }
1521
                        linksToStop = append(linksToStop, pendingLink)
3✔
1522
                }
1523
                s.indexMtx.Unlock()
3✔
1524

3✔
1525
                // Now that all pending and live links have been removed from
3✔
1526
                // the forwarding indexes, stop each one before shutting down.
3✔
1527
                // We'll shut them down in parallel to make exiting as fast as
3✔
1528
                // possible.
3✔
1529
                var wg sync.WaitGroup
3✔
1530
                for _, link := range linksToStop {
6✔
1531
                        wg.Add(1)
3✔
1532
                        go func(l ChannelLink) {
6✔
1533
                                defer wg.Done()
3✔
1534

3✔
1535
                                l.Stop()
3✔
1536
                        }(link)
3✔
1537
                }
1538
                wg.Wait()
3✔
1539

3✔
1540
                // Before we exit fully, we'll attempt to flush out any
3✔
1541
                // forwarding events that may still be lingering since the last
3✔
1542
                // batch flush.
3✔
1543
                if err := s.FlushForwardingEvents(); err != nil {
3✔
1544
                        log.Errorf("unable to flush forwarding events: %v", err)
×
1545
                }
×
1546
        }()
1547

1548
        // TODO(roasbeef): cleared vs settled distinction
1549
        var (
3✔
1550
                totalNumUpdates uint64
3✔
1551
                totalSatSent    btcutil.Amount
3✔
1552
                totalSatRecv    btcutil.Amount
3✔
1553
        )
3✔
1554
        s.cfg.LogEventTicker.Resume()
3✔
1555
        defer s.cfg.LogEventTicker.Stop()
3✔
1556

3✔
1557
        // Every 15 seconds, we'll flush out the forwarding events that
3✔
1558
        // occurred during that period.
3✔
1559
        s.cfg.FwdEventTicker.Resume()
3✔
1560
        defer s.cfg.FwdEventTicker.Stop()
3✔
1561

3✔
1562
        defer s.cfg.AckEventTicker.Stop()
3✔
1563

3✔
1564
out:
3✔
1565
        for {
6✔
1566

3✔
1567
                // If the set of pending settle/fail entries is non-zero,
3✔
1568
                // reinstate the ack ticker so we can batch ack them.
3✔
1569
                if len(s.pendingSettleFails) > 0 {
6✔
1570
                        s.cfg.AckEventTicker.Resume()
3✔
1571
                }
3✔
1572

1573
                select {
3✔
1574
                case blockEpoch, ok := <-s.blockEpochStream.Epochs:
3✔
1575
                        if !ok {
3✔
1576
                                break out
×
1577
                        }
1578

1579
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
3✔
1580

1581
                // A local close request has arrived, we'll forward this to the
1582
                // relevant link (if it exists) so the channel can be
1583
                // cooperatively closed (if possible).
1584
                case req := <-s.chanCloseRequests:
3✔
1585
                        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
3✔
1586

3✔
1587
                        s.indexMtx.RLock()
3✔
1588
                        link, ok := s.linkIndex[chanID]
3✔
1589
                        if !ok {
6✔
1590
                                s.indexMtx.RUnlock()
3✔
1591

3✔
1592
                                req.Err <- fmt.Errorf("no peer for channel with "+
3✔
1593
                                        "chan_id=%x", chanID[:])
3✔
1594
                                continue
3✔
1595
                        }
1596
                        s.indexMtx.RUnlock()
3✔
1597

3✔
1598
                        peerPub := link.PeerPubKey()
3✔
1599
                        log.Debugf("Requesting local channel close: peer=%x, "+
3✔
1600
                                "chan_id=%x", link.PeerPubKey(), chanID[:])
3✔
1601

3✔
1602
                        go s.cfg.LocalChannelClose(peerPub[:], req)
3✔
1603

1604
                case resolutionMsg := <-s.resolutionMsgs:
3✔
1605
                        // We'll persist the resolution message to the Switch's
3✔
1606
                        // resolution store.
3✔
1607
                        resMsg := resolutionMsg.ResolutionMsg
3✔
1608
                        err := s.resMsgStore.addResolutionMsg(&resMsg)
3✔
1609
                        if err != nil {
3✔
1610
                                // This will only fail if there is a database
×
1611
                                // error or a serialization error. Sending the
×
1612
                                // error prevents the contractcourt from being
×
1613
                                // in a state where it believes the send was
×
1614
                                // successful, when it wasn't.
×
1615
                                log.Errorf("unable to add resolution msg: %v",
×
1616
                                        err)
×
1617
                                resolutionMsg.errChan <- err
×
1618
                                continue
×
1619
                        }
1620

1621
                        // At this point, the resolution message has been
1622
                        // persisted. It is safe to signal success by sending
1623
                        // a nil error since the Switch will re-deliver the
1624
                        // resolution message on restart.
1625
                        resolutionMsg.errChan <- nil
3✔
1626

3✔
1627
                        // Create a htlc packet for this resolution. We do
3✔
1628
                        // not have some of the information that we'll need
3✔
1629
                        // for blinded error handling here , so we'll rely on
3✔
1630
                        // our forwarding logic to fill it in later.
3✔
1631
                        pkt := &htlcPacket{
3✔
1632
                                outgoingChanID: resolutionMsg.SourceChan,
3✔
1633
                                outgoingHTLCID: resolutionMsg.HtlcIndex,
3✔
1634
                                isResolution:   true,
3✔
1635
                        }
3✔
1636

3✔
1637
                        // Resolution messages will either be cancelling
3✔
1638
                        // backwards an existing HTLC, or settling a previously
3✔
1639
                        // outgoing HTLC. Based on this, we'll map the message
3✔
1640
                        // to the proper htlcPacket.
3✔
1641
                        if resolutionMsg.Failure != nil {
6✔
1642
                                pkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1643
                        } else {
6✔
1644
                                pkt.htlc = &lnwire.UpdateFulfillHTLC{
3✔
1645
                                        PaymentPreimage: *resolutionMsg.PreImage,
3✔
1646
                                }
3✔
1647
                        }
3✔
1648

1649
                        log.Debugf("Received outside contract resolution, "+
3✔
1650
                                "mapping to: %v", spew.Sdump(pkt))
3✔
1651

3✔
1652
                        // We don't check the error, as the only failure we can
3✔
1653
                        // encounter is due to the circuit already being
3✔
1654
                        // closed. This is fine, as processing this message is
3✔
1655
                        // meant to be idempotent.
3✔
1656
                        err = s.handlePacketForward(pkt)
3✔
1657
                        if err != nil {
3✔
1658
                                log.Errorf("Unable to forward resolution msg: %v", err)
×
1659
                        }
×
1660

1661
                // A new packet has arrived for forwarding, we'll interpret the
1662
                // packet concretely, then either forward it along, or
1663
                // interpret a return packet to a locally initialized one.
1664
                case cmd := <-s.htlcPlex:
3✔
1665
                        cmd.err <- s.handlePacketForward(cmd.pkt)
3✔
1666

1667
                // When this time ticks, then it indicates that we should
1668
                // collect all the forwarding events since the last internal,
1669
                // and write them out to our log.
1670
                case <-s.cfg.FwdEventTicker.Ticks():
3✔
1671
                        s.wg.Add(1)
3✔
1672
                        go func() {
6✔
1673
                                defer s.wg.Done()
3✔
1674

3✔
1675
                                if err := s.FlushForwardingEvents(); err != nil {
3✔
1676
                                        log.Errorf("Unable to flush "+
×
1677
                                                "forwarding events: %v", err)
×
1678
                                }
×
1679
                        }()
1680

1681
                // The log ticker has fired, so we'll calculate some forwarding
1682
                // stats for the last 10 seconds to display within the logs to
1683
                // users.
1684
                case <-s.cfg.LogEventTicker.Ticks():
3✔
1685
                        // First, we'll collate the current running tally of
3✔
1686
                        // our forwarding stats.
3✔
1687
                        prevSatSent := totalSatSent
3✔
1688
                        prevSatRecv := totalSatRecv
3✔
1689
                        prevNumUpdates := totalNumUpdates
3✔
1690

3✔
1691
                        var (
3✔
1692
                                newNumUpdates uint64
3✔
1693
                                newSatSent    btcutil.Amount
3✔
1694
                                newSatRecv    btcutil.Amount
3✔
1695
                        )
3✔
1696

3✔
1697
                        // Next, we'll run through all the registered links and
3✔
1698
                        // compute their up-to-date forwarding stats.
3✔
1699
                        s.indexMtx.RLock()
3✔
1700
                        for _, link := range s.linkIndex {
6✔
1701
                                // TODO(roasbeef): when links first registered
3✔
1702
                                // stats printed.
3✔
1703
                                updates, sent, recv := link.Stats()
3✔
1704
                                newNumUpdates += updates
3✔
1705
                                newSatSent += sent.ToSatoshis()
3✔
1706
                                newSatRecv += recv.ToSatoshis()
3✔
1707
                        }
3✔
1708
                        s.indexMtx.RUnlock()
3✔
1709

3✔
1710
                        var (
3✔
1711
                                diffNumUpdates uint64
3✔
1712
                                diffSatSent    btcutil.Amount
3✔
1713
                                diffSatRecv    btcutil.Amount
3✔
1714
                        )
3✔
1715

3✔
1716
                        // If this is the first time we're computing these
3✔
1717
                        // stats, then the diff is just the new value. We do
3✔
1718
                        // this in order to avoid integer underflow issues.
3✔
1719
                        if prevNumUpdates == 0 {
6✔
1720
                                diffNumUpdates = newNumUpdates
3✔
1721
                                diffSatSent = newSatSent
3✔
1722
                                diffSatRecv = newSatRecv
3✔
1723
                        } else {
6✔
1724
                                diffNumUpdates = newNumUpdates - prevNumUpdates
3✔
1725
                                diffSatSent = newSatSent - prevSatSent
3✔
1726
                                diffSatRecv = newSatRecv - prevSatRecv
3✔
1727
                        }
3✔
1728

1729
                        // If the diff of num updates is zero, then we haven't
1730
                        // forwarded anything in the last 10 seconds, so we can
1731
                        // skip this update.
1732
                        if diffNumUpdates == 0 {
6✔
1733
                                continue
3✔
1734
                        }
1735

1736
                        // If the diff of num updates is negative, then some
1737
                        // links may have been unregistered from the switch, so
1738
                        // we'll update our stats to only include our registered
1739
                        // links.
1740
                        if int64(diffNumUpdates) < 0 {
6✔
1741
                                totalNumUpdates = newNumUpdates
3✔
1742
                                totalSatSent = newSatSent
3✔
1743
                                totalSatRecv = newSatRecv
3✔
1744
                                continue
3✔
1745
                        }
1746

1747
                        // Otherwise, we'll log this diff, then accumulate the
1748
                        // new stats into the running total.
1749
                        log.Debugf("Sent %d satoshis and received %d satoshis "+
3✔
1750
                                "in the last 10 seconds (%f tx/sec)",
3✔
1751
                                diffSatSent, diffSatRecv,
3✔
1752
                                float64(diffNumUpdates)/10)
3✔
1753

3✔
1754
                        totalNumUpdates += diffNumUpdates
3✔
1755
                        totalSatSent += diffSatSent
3✔
1756
                        totalSatRecv += diffSatRecv
3✔
1757

1758
                // The ack ticker has fired so if we have any settle/fail entries
1759
                // for a forwarding package to ack, we will do so here in a batch
1760
                // db call.
1761
                case <-s.cfg.AckEventTicker.Ticks():
3✔
1762
                        // If the current set is empty, pause the ticker.
3✔
1763
                        if len(s.pendingSettleFails) == 0 {
6✔
1764
                                s.cfg.AckEventTicker.Pause()
3✔
1765
                                continue
3✔
1766
                        }
1767

1768
                        // Batch ack the settle/fail entries.
1769
                        if err := s.ackSettleFail(s.pendingSettleFails...); err != nil {
3✔
1770
                                log.Errorf("Unable to ack batch of settle/fails: %v", err)
×
1771
                                continue
×
1772
                        }
1773

1774
                        log.Tracef("Acked %d settle fails: %v",
3✔
1775
                                len(s.pendingSettleFails),
3✔
1776
                                lnutils.SpewLogClosure(s.pendingSettleFails))
3✔
1777

3✔
1778
                        // Reset the pendingSettleFails buffer while keeping acquired
3✔
1779
                        // memory.
3✔
1780
                        s.pendingSettleFails = s.pendingSettleFails[:0]
3✔
1781

1782
                case <-s.quit:
3✔
1783
                        return
3✔
1784
                }
1785
        }
1786
}
1787

1788
// Start starts all helper goroutines required for the operation of the switch.
1789
func (s *Switch) Start() error {
3✔
1790
        if !atomic.CompareAndSwapInt32(&s.started, 0, 1) {
3✔
1791
                log.Warn("Htlc Switch already started")
×
1792
                return errors.New("htlc switch already started")
×
1793
        }
×
1794

1795
        log.Infof("HTLC Switch starting")
3✔
1796

3✔
1797
        blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
1798
        if err != nil {
3✔
1799
                return err
×
1800
        }
×
1801
        s.blockEpochStream = blockEpochStream
3✔
1802

3✔
1803
        s.wg.Add(1)
3✔
1804
        go s.htlcForwarder()
3✔
1805

3✔
1806
        if err := s.reforwardResponses(); err != nil {
3✔
1807
                s.Stop()
×
1808
                log.Errorf("unable to reforward responses: %v", err)
×
1809
                return err
×
1810
        }
×
1811

1812
        if err := s.reforwardResolutions(); err != nil {
3✔
1813
                // We are already stopping so we can ignore the error.
×
1814
                _ = s.Stop()
×
1815
                log.Errorf("unable to reforward resolutions: %v", err)
×
1816
                return err
×
1817
        }
×
1818

1819
        return nil
3✔
1820
}
1821

1822
// reforwardResolutions fetches the set of resolution messages stored on-disk
1823
// and reforwards them if their circuits are still open. If the circuits have
1824
// been deleted, then we will delete the resolution message from the database.
1825
func (s *Switch) reforwardResolutions() error {
3✔
1826
        // Fetch all stored resolution messages, deleting the ones that are
3✔
1827
        // resolved.
3✔
1828
        resMsgs, err := s.resMsgStore.fetchAllResolutionMsg()
3✔
1829
        if err != nil {
3✔
1830
                return err
×
1831
        }
×
1832

1833
        switchPackets := make([]*htlcPacket, 0, len(resMsgs))
3✔
1834
        for _, resMsg := range resMsgs {
6✔
1835
                // If the open circuit no longer exists, then we can remove the
3✔
1836
                // message from the store.
3✔
1837
                outKey := CircuitKey{
3✔
1838
                        ChanID: resMsg.SourceChan,
3✔
1839
                        HtlcID: resMsg.HtlcIndex,
3✔
1840
                }
3✔
1841

3✔
1842
                if s.circuits.LookupOpenCircuit(outKey) == nil {
6✔
1843
                        // The open circuit doesn't exist.
3✔
1844
                        err := s.resMsgStore.deleteResolutionMsg(&outKey)
3✔
1845
                        if err != nil {
3✔
1846
                                return err
×
1847
                        }
×
1848

1849
                        continue
3✔
1850
                }
1851

1852
                // The circuit is still open, so we can assume that the link or
1853
                // switch (if we are the source) hasn't cleaned it up yet.
1854
                // We rely on our forwarding logic to fill in details that
1855
                // are not currently available to us.
1856
                resPkt := &htlcPacket{
3✔
1857
                        outgoingChanID: resMsg.SourceChan,
3✔
1858
                        outgoingHTLCID: resMsg.HtlcIndex,
3✔
1859
                        isResolution:   true,
3✔
1860
                }
3✔
1861

3✔
1862
                if resMsg.Failure != nil {
6✔
1863
                        resPkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1864
                } else {
3✔
1865
                        resPkt.htlc = &lnwire.UpdateFulfillHTLC{
×
1866
                                PaymentPreimage: *resMsg.PreImage,
×
1867
                        }
×
1868
                }
×
1869

1870
                switchPackets = append(switchPackets, resPkt)
3✔
1871
        }
1872

1873
        // We'll now dispatch the set of resolution messages to the proper
1874
        // destination. An error is only encountered here if the switch is
1875
        // shutting down.
1876
        if err := s.ForwardPackets(nil, switchPackets...); err != nil {
3✔
1877
                return err
×
1878
        }
×
1879

1880
        return nil
3✔
1881
}
1882

1883
// reforwardResponses for every known, non-pending channel, loads all associated
1884
// forwarding packages and reforwards any Settle or Fail HTLCs found. This is
1885
// used to resurrect the switch's mailboxes after a restart. This also runs for
1886
// waiting close channels since there may be settles or fails that need to be
1887
// reforwarded before they completely close.
1888
func (s *Switch) reforwardResponses() error {
3✔
1889
        openChannels, err := s.cfg.FetchAllChannels()
3✔
1890
        if err != nil {
3✔
1891
                return err
×
1892
        }
×
1893

1894
        for _, openChannel := range openChannels {
6✔
1895
                shortChanID := openChannel.ShortChanID()
3✔
1896

3✔
1897
                // Locally-initiated payments never need reforwarding.
3✔
1898
                if shortChanID == hop.Source {
6✔
1899
                        continue
3✔
1900
                }
1901

1902
                // If the channel is pending, it should have no forwarding
1903
                // packages, and nothing to reforward.
1904
                if openChannel.IsPending {
3✔
1905
                        continue
×
1906
                }
1907

1908
                // Channels in open or waiting-close may still have responses in
1909
                // their forwarding packages. We will continue to reattempt
1910
                // forwarding on startup until the channel is fully-closed.
1911
                //
1912
                // Load this channel's forwarding packages, and deliver them to
1913
                // the switch.
1914
                fwdPkgs, err := s.loadChannelFwdPkgs(shortChanID)
3✔
1915
                if err != nil {
3✔
1916
                        log.Errorf("unable to load forwarding "+
×
1917
                                "packages for %v: %v", shortChanID, err)
×
1918
                        return err
×
1919
                }
×
1920

1921
                s.reforwardSettleFails(fwdPkgs)
3✔
1922
        }
1923

1924
        return nil
3✔
1925
}
1926

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

3✔
1931
        var fwdPkgs []*channeldb.FwdPkg
3✔
1932
        if err := kvdb.View(s.cfg.DB, func(tx kvdb.RTx) error {
6✔
1933
                var err error
3✔
1934
                fwdPkgs, err = s.cfg.SwitchPackager.LoadChannelFwdPkgs(
3✔
1935
                        tx, source,
3✔
1936
                )
3✔
1937
                return err
3✔
1938
        }, func() {
6✔
1939
                fwdPkgs = nil
3✔
1940
        }); err != nil {
3✔
1941
                return nil, err
×
1942
        }
×
1943

1944
        return fwdPkgs, nil
3✔
1945
}
1946

1947
// reforwardSettleFails parses the Settle and Fail HTLCs from the list of
1948
// forwarding packages, and reforwards those that have not been acknowledged.
1949
// This is intended to occur on startup, in order to recover the switch's
1950
// mailboxes, and to ensure that responses can be propagated in case the
1951
// outgoing link never comes back online.
1952
//
1953
// NOTE: This should mimic the behavior processRemoteSettleFails.
1954
func (s *Switch) reforwardSettleFails(fwdPkgs []*channeldb.FwdPkg) {
3✔
1955
        for _, fwdPkg := range fwdPkgs {
6✔
1956
                switchPackets := make([]*htlcPacket, 0, len(fwdPkg.SettleFails))
3✔
1957
                for i, update := range fwdPkg.SettleFails {
6✔
1958
                        // Skip any settles or fails that have already been
3✔
1959
                        // acknowledged by the incoming link that originated the
3✔
1960
                        // forwarded Add.
3✔
1961
                        if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
6✔
1962
                                continue
3✔
1963
                        }
1964

1965
                        switch msg := update.UpdateMsg.(type) {
3✔
1966
                        // A settle for an HTLC we previously forwarded HTLC has
1967
                        // been received. So we'll forward the HTLC to the
1968
                        // switch which will handle propagating the settle to
1969
                        // the prior hop.
1970
                        case *lnwire.UpdateFulfillHTLC:
3✔
1971
                                destRef := fwdPkg.DestRef(uint16(i))
3✔
1972
                                settlePacket := &htlcPacket{
3✔
1973
                                        outgoingChanID: fwdPkg.Source,
3✔
1974
                                        outgoingHTLCID: msg.ID,
3✔
1975
                                        destRef:        &destRef,
3✔
1976
                                        htlc:           msg,
3✔
1977
                                }
3✔
1978

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

1984
                        // A failureCode message for a previously forwarded HTLC has been
1985
                        // received. As a result a new slot will be freed up in our
1986
                        // commitment state, so we'll forward this to the switch so the
1987
                        // backwards undo can continue.
1988
                        case *lnwire.UpdateFailHTLC:
×
1989
                                // Fetch the reason the HTLC was canceled so
×
1990
                                // we can continue to propagate it. This
×
1991
                                // failure originated from another node, so
×
1992
                                // the linkFailure field is not set on this
×
1993
                                // packet. We rely on the link to fill in
×
1994
                                // additional circuit information for us.
×
1995
                                failPacket := &htlcPacket{
×
1996
                                        outgoingChanID: fwdPkg.Source,
×
1997
                                        outgoingHTLCID: msg.ID,
×
1998
                                        destRef: &channeldb.SettleFailRef{
×
1999
                                                Source: fwdPkg.Source,
×
2000
                                                Height: fwdPkg.Height,
×
2001
                                                Index:  uint16(i),
×
2002
                                        },
×
2003
                                        htlc: msg,
×
2004
                                }
×
2005

×
2006
                                // Add the packet to the batch to be forwarded, and
×
2007
                                // notify the overflow queue that a spare spot has been
×
2008
                                // freed up within the commitment state.
×
2009
                                switchPackets = append(switchPackets, failPacket)
×
2010
                        }
2011
                }
2012

2013
                // Since this send isn't tied to a specific link, we pass a nil
2014
                // link quit channel, meaning the send will fail only if the
2015
                // switch receives a shutdown request.
2016
                if err := s.ForwardPackets(nil, switchPackets...); err != nil {
3✔
2017
                        log.Errorf("Unhandled error while reforwarding packets "+
×
2018
                                "settle/fail over htlcswitch: %v", err)
×
2019
                }
×
2020
        }
2021
}
2022

2023
// Stop gracefully stops all active helper goroutines, then waits until they've
2024
// exited.
2025
func (s *Switch) Stop() error {
3✔
2026
        if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
3✔
2027
                log.Warn("Htlc Switch already stopped")
×
2028
                return errors.New("htlc switch already shutdown")
×
2029
        }
×
2030

2031
        log.Info("HTLC Switch shutting down...")
3✔
2032
        defer log.Debug("HTLC Switch shutdown complete")
3✔
2033

3✔
2034
        close(s.quit)
3✔
2035

3✔
2036
        s.wg.Wait()
3✔
2037

3✔
2038
        // Wait until all active goroutines have finished exiting before
3✔
2039
        // stopping the mailboxes, otherwise the mailbox map could still be
3✔
2040
        // accessed and modified.
3✔
2041
        s.mailOrchestrator.Stop()
3✔
2042

3✔
2043
        return nil
3✔
2044
}
2045

2046
// CreateAndAddLink will create a link and then add it to the internal maps
2047
// when given a ChannelLinkConfig and LightningChannel.
2048
func (s *Switch) CreateAndAddLink(linkCfg ChannelLinkConfig,
2049
        lnChan *lnwallet.LightningChannel) error {
3✔
2050

3✔
2051
        link := NewChannelLink(linkCfg, lnChan)
3✔
2052
        return s.AddLink(link)
3✔
2053
}
3✔
2054

2055
// AddLink is used to initiate the handling of the add link command. The
2056
// request will be propagated and handled in the main goroutine.
2057
func (s *Switch) AddLink(link ChannelLink) error {
3✔
2058
        s.indexMtx.Lock()
3✔
2059
        defer s.indexMtx.Unlock()
3✔
2060

3✔
2061
        chanID := link.ChanID()
3✔
2062

3✔
2063
        // First, ensure that this link is not already active in the switch.
3✔
2064
        _, err := s.getLink(chanID)
3✔
2065
        if err == nil {
3✔
2066
                return fmt.Errorf("unable to add ChannelLink(%v), already "+
×
2067
                        "active", chanID)
×
2068
        }
×
2069

2070
        // Get and attach the mailbox for this link, which buffers packets in
2071
        // case there packets that we tried to deliver while this link was
2072
        // offline.
2073
        shortChanID := link.ShortChanID()
3✔
2074
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(chanID, shortChanID)
3✔
2075
        link.AttachMailBox(mailbox)
3✔
2076

3✔
2077
        // Attach the Switch's failAliasUpdate function to the link.
3✔
2078
        link.attachFailAliasUpdate(s.failAliasUpdate)
3✔
2079

3✔
2080
        if err := link.Start(); err != nil {
3✔
2081
                log.Errorf("AddLink failed to start link with chanID=%v: %v",
×
2082
                        chanID, err)
×
2083
                s.removeLink(chanID)
×
2084
                return err
×
2085
        }
×
2086

2087
        if shortChanID == hop.Source {
6✔
2088
                log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
3✔
2089
                        chanID, shortChanID)
3✔
2090

3✔
2091
                s.pendingLinkIndex[chanID] = link
3✔
2092
        } else {
6✔
2093
                log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
3✔
2094
                        chanID, shortChanID)
3✔
2095

3✔
2096
                s.addLiveLink(link)
3✔
2097
                s.mailOrchestrator.BindLiveShortChanID(
3✔
2098
                        mailbox, chanID, shortChanID,
3✔
2099
                )
3✔
2100
        }
3✔
2101

2102
        return nil
3✔
2103
}
2104

2105
// addLiveLink adds a link to all associated forwarding index, this makes it a
2106
// candidate for forwarding HTLCs.
2107
func (s *Switch) addLiveLink(link ChannelLink) {
3✔
2108
        linkScid := link.ShortChanID()
3✔
2109

3✔
2110
        // We'll add the link to the linkIndex which lets us quickly
3✔
2111
        // look up a channel when we need to close or register it, and
3✔
2112
        // the forwarding index which'll be used when forwarding HTLC's
3✔
2113
        // in the multi-hop setting.
3✔
2114
        s.linkIndex[link.ChanID()] = link
3✔
2115
        s.forwardingIndex[linkScid] = link
3✔
2116

3✔
2117
        // Next we'll add the link to the interface index so we can
3✔
2118
        // quickly look up all the channels for a particular node.
3✔
2119
        peerPub := link.PeerPubKey()
3✔
2120
        if _, ok := s.interfaceIndex[peerPub]; !ok {
6✔
2121
                s.interfaceIndex[peerPub] = make(map[lnwire.ChannelID]ChannelLink)
3✔
2122
        }
3✔
2123
        s.interfaceIndex[peerPub][link.ChanID()] = link
3✔
2124

3✔
2125
        s.updateLinkAliases(link)
3✔
2126
}
2127

2128
// UpdateLinkAliases is the externally exposed wrapper for updating link
2129
// aliases. It acquires the indexMtx and calls the internal method.
2130
func (s *Switch) UpdateLinkAliases(link ChannelLink) {
3✔
2131
        s.indexMtx.Lock()
3✔
2132
        defer s.indexMtx.Unlock()
3✔
2133

3✔
2134
        s.updateLinkAliases(link)
3✔
2135
}
3✔
2136

2137
// updateLinkAliases updates the aliases for a given link. This will cause the
2138
// htlcswitch to consult the alias manager on the up to date values of its
2139
// alias maps.
2140
//
2141
// NOTE: this MUST be called with the indexMtx held.
2142
func (s *Switch) updateLinkAliases(link ChannelLink) {
3✔
2143
        linkScid := link.ShortChanID()
3✔
2144

3✔
2145
        aliases := link.getAliases()
3✔
2146
        if link.isZeroConf() {
6✔
2147
                if link.zeroConfConfirmed() {
6✔
2148
                        // Since the zero-conf channel has confirmed, we can
3✔
2149
                        // populate the aliasToReal mapping.
3✔
2150
                        confirmedScid := link.confirmedScid()
3✔
2151

3✔
2152
                        for _, alias := range aliases {
6✔
2153
                                s.aliasToReal[alias] = confirmedScid
3✔
2154
                        }
3✔
2155

2156
                        // Add the confirmed SCID as a key in the baseIndex.
2157
                        s.baseIndex[confirmedScid] = linkScid
3✔
2158
                }
2159

2160
                // Now we populate the baseIndex which will be used to fetch
2161
                // the link given any of the channel's alias SCIDs or the real
2162
                // SCID. The link's SCID is an alias, so we don't need to
2163
                // special-case it like the option-scid-alias feature-bit case
2164
                // further down.
2165
                for _, alias := range aliases {
6✔
2166
                        s.baseIndex[alias] = linkScid
3✔
2167
                }
3✔
2168
        } else if link.negotiatedAliasFeature() {
6✔
2169
                // First, we flush any alias mappings for this link's scid
3✔
2170
                // before we populate the map again, in order to get rid of old
3✔
2171
                // values that no longer exist.
3✔
2172
                for alias, real := range s.aliasToReal {
6✔
2173
                        if real == linkScid {
6✔
2174
                                delete(s.aliasToReal, alias)
3✔
2175
                        }
3✔
2176
                }
2177

2178
                for alias, real := range s.baseIndex {
6✔
2179
                        if real == linkScid {
6✔
2180
                                delete(s.baseIndex, alias)
3✔
2181
                        }
3✔
2182
                }
2183

2184
                // The link's SCID is the confirmed SCID for non-zero-conf
2185
                // option-scid-alias feature bit channels.
2186
                for _, alias := range aliases {
6✔
2187
                        s.aliasToReal[alias] = linkScid
3✔
2188
                        s.baseIndex[alias] = linkScid
3✔
2189
                }
3✔
2190

2191
                // Since the link's SCID is confirmed, it was not included in
2192
                // the baseIndex above as a key. Add it now.
2193
                s.baseIndex[linkScid] = linkScid
3✔
2194
        }
2195
}
2196

2197
// GetLink is used to initiate the handling of the get link command. The
2198
// request will be propagated/handled to/in the main goroutine.
2199
func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelUpdateHandler,
2200
        error) {
3✔
2201

3✔
2202
        s.indexMtx.RLock()
3✔
2203
        defer s.indexMtx.RUnlock()
3✔
2204

3✔
2205
        return s.getLink(chanID)
3✔
2206
}
3✔
2207

2208
// getLink returns the link stored in either the pending index or the live
2209
// lindex.
2210
func (s *Switch) getLink(chanID lnwire.ChannelID) (ChannelLink, error) {
3✔
2211
        link, ok := s.linkIndex[chanID]
3✔
2212
        if !ok {
6✔
2213
                link, ok = s.pendingLinkIndex[chanID]
3✔
2214
                if !ok {
6✔
2215
                        return nil, ErrChannelLinkNotFound
3✔
2216
                }
3✔
2217
        }
2218

2219
        return link, nil
3✔
2220
}
2221

2222
// GetLinkByShortID attempts to return the link which possesses the target short
2223
// channel ID.
2224
func (s *Switch) GetLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink,
2225
        error) {
3✔
2226

3✔
2227
        s.indexMtx.RLock()
3✔
2228
        defer s.indexMtx.RUnlock()
3✔
2229

3✔
2230
        link, err := s.getLinkByShortID(chanID)
3✔
2231
        if err != nil {
6✔
2232
                // If we failed to find the link under the passed-in SCID, we
3✔
2233
                // consult the Switch's baseIndex map to see if the confirmed
3✔
2234
                // SCID was used for a zero-conf channel.
3✔
2235
                aliasID, ok := s.baseIndex[chanID]
3✔
2236
                if !ok {
6✔
2237
                        return nil, err
3✔
2238
                }
3✔
2239

2240
                // An alias was found, use it to lookup if a link exists.
2241
                return s.getLinkByShortID(aliasID)
3✔
2242
        }
2243

2244
        return link, nil
3✔
2245
}
2246

2247
// getLinkByShortID attempts to return the link which possesses the target
2248
// short channel ID.
2249
//
2250
// NOTE: This MUST be called with the indexMtx held.
2251
func (s *Switch) getLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink, error) {
3✔
2252
        link, ok := s.forwardingIndex[chanID]
3✔
2253
        if !ok {
6✔
2254
                return nil, ErrChannelLinkNotFound
3✔
2255
        }
3✔
2256

2257
        return link, nil
3✔
2258
}
2259

2260
// getLinkByMapping attempts to fetch the link via the htlcPacket's
2261
// outgoingChanID, possibly using a mapping. If it finds the link via mapping,
2262
// the outgoingChanID will be changed so that an error can be properly
2263
// attributed when looping over linkErrs in handlePacketForward.
2264
//
2265
// * If the outgoingChanID is an alias, we'll fetch the link regardless if it's
2266
// public or not.
2267
//
2268
// * If the outgoingChanID is a confirmed SCID, we'll need to do more checks.
2269
//   - If there is no entry found in baseIndex, fetch the link. This channel
2270
//     did not have the option-scid-alias feature negotiated (which includes
2271
//     zero-conf and option-scid-alias channel-types).
2272
//   - If there is an entry found, fetch the link from forwardingIndex and
2273
//     fail if this is a private link.
2274
//
2275
// NOTE: This MUST be called with the indexMtx read lock held.
2276
func (s *Switch) getLinkByMapping(pkt *htlcPacket) (ChannelLink, error) {
3✔
2277
        // Determine if this ShortChannelID is an alias or a confirmed SCID.
3✔
2278
        chanID := pkt.outgoingChanID
3✔
2279
        aliasID := s.cfg.IsAlias(chanID)
3✔
2280

3✔
2281
        log.Debugf("Querying outgoing link using chanID=%v, aliasID=%v", chanID,
3✔
2282
                aliasID)
3✔
2283

3✔
2284
        // Set the originalOutgoingChanID so the proper channel_update can be
3✔
2285
        // sent back if the option-scid-alias feature bit was negotiated.
3✔
2286
        pkt.originalOutgoingChanID = chanID
3✔
2287

3✔
2288
        if aliasID {
6✔
2289
                // Since outgoingChanID is an alias, we'll fetch the link via
3✔
2290
                // baseIndex.
3✔
2291
                baseScid, ok := s.baseIndex[chanID]
3✔
2292
                if !ok {
3✔
2293
                        // No mapping exists, bail.
×
2294
                        return nil, ErrChannelLinkNotFound
×
2295
                }
×
2296

2297
                // A mapping exists, so use baseScid to find the link in the
2298
                // forwardingIndex.
2299
                link, ok := s.forwardingIndex[baseScid]
3✔
2300
                if !ok {
3✔
2301
                        log.Debugf("Forwarding index not found using "+
×
2302
                                "baseScid=%v", baseScid)
×
2303

×
2304
                        // Link not found, bail.
×
2305
                        return nil, ErrChannelLinkNotFound
×
2306
                }
×
2307

2308
                // Change the packet's outgoingChanID field so that errors are
2309
                // properly attributed.
2310
                pkt.outgoingChanID = baseScid
3✔
2311

3✔
2312
                // Return the link without checking if it's private or not.
3✔
2313
                return link, nil
3✔
2314
        }
2315

2316
        // The outgoingChanID is a confirmed SCID. Attempt to fetch the base
2317
        // SCID from baseIndex.
2318
        baseScid, ok := s.baseIndex[chanID]
3✔
2319
        if !ok {
6✔
2320
                // outgoingChanID is not a key in base index meaning this
3✔
2321
                // channel did not have the option-scid-alias feature bit
3✔
2322
                // negotiated. We'll fetch the link and return it.
3✔
2323
                link, ok := s.forwardingIndex[chanID]
3✔
2324
                if !ok {
6✔
2325
                        log.Debugf("Forwarding index not found using "+
3✔
2326
                                "chanID=%v", chanID)
3✔
2327

3✔
2328
                        // The link wasn't found, bail out.
3✔
2329
                        return nil, ErrChannelLinkNotFound
3✔
2330
                }
3✔
2331

2332
                return link, nil
3✔
2333
        }
2334

2335
        // Fetch the link whose internal SCID is baseScid.
2336
        link, ok := s.forwardingIndex[baseScid]
3✔
2337
        if !ok {
3✔
2338
                log.Debugf("Forwarding index not found using baseScid=%v",
×
2339
                        baseScid)
×
2340

×
2341
                // Link wasn't found, bail out.
×
2342
                return nil, ErrChannelLinkNotFound
×
2343
        }
×
2344

2345
        // If the link is unadvertised, we fail since the real SCID was used to
2346
        // forward over it and this is a channel where the option-scid-alias
2347
        // feature bit was negotiated.
2348
        if link.IsUnadvertised() {
3✔
2349
                log.Debugf("Link is unadvertised, chanID=%v, baseScid=%v",
×
2350
                        chanID, baseScid)
×
2351

×
2352
                return nil, ErrChannelLinkNotFound
×
2353
        }
×
2354

2355
        // The link is public so the confirmed SCID can be used to forward over
2356
        // it. We'll also replace pkt's outgoingChanID field so errors can
2357
        // properly be attributed in the calling function.
2358
        pkt.outgoingChanID = baseScid
3✔
2359
        return link, nil
3✔
2360
}
2361

2362
// HasActiveLink returns true if the given channel ID has a link in the link
2363
// index AND the link is eligible to forward.
2364
func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
3✔
2365
        s.indexMtx.RLock()
3✔
2366
        defer s.indexMtx.RUnlock()
3✔
2367

3✔
2368
        if link, ok := s.linkIndex[chanID]; ok {
6✔
2369
                return link.EligibleToForward()
3✔
2370
        }
3✔
2371

2372
        return false
3✔
2373
}
2374

2375
// RemoveLink purges the switch of any link associated with chanID. If a pending
2376
// or active link is not found, this method does nothing. Otherwise, the method
2377
// returns after the link has been completely shutdown.
2378
func (s *Switch) RemoveLink(chanID lnwire.ChannelID) {
3✔
2379
        s.indexMtx.Lock()
3✔
2380
        link, err := s.getLink(chanID)
3✔
2381
        if err != nil {
6✔
2382
                // If err is non-nil, this means that link is also nil. The
3✔
2383
                // link variable cannot be nil without err being non-nil.
3✔
2384
                s.indexMtx.Unlock()
3✔
2385
                log.Tracef("Unable to remove link for ChannelID(%v): %v",
3✔
2386
                        chanID, err)
3✔
2387
                return
3✔
2388
        }
3✔
2389

2390
        // Check if the link is already stopping and grab the stop chan if it
2391
        // is.
2392
        stopChan, ok := s.linkStopIndex[chanID]
3✔
2393
        if !ok {
6✔
2394
                // If the link is non-nil, it is not currently stopping, so
3✔
2395
                // we'll add a stop chan to the linkStopIndex.
3✔
2396
                stopChan = make(chan struct{})
3✔
2397
                s.linkStopIndex[chanID] = stopChan
3✔
2398
        }
3✔
2399
        s.indexMtx.Unlock()
3✔
2400

3✔
2401
        if ok {
3✔
2402
                // If the stop chan exists, we will wait for it to be closed.
×
2403
                // Once it is closed, we will exit.
×
2404
                select {
×
2405
                case <-stopChan:
×
2406
                        return
×
2407
                case <-s.quit:
×
2408
                        return
×
2409
                }
2410
        }
2411

2412
        // Stop the link before removing it from the maps.
2413
        link.Stop()
3✔
2414

3✔
2415
        s.indexMtx.Lock()
3✔
2416
        _ = s.removeLink(chanID)
3✔
2417

3✔
2418
        // Close stopChan and remove this link from the linkStopIndex.
3✔
2419
        // Deleting from the index and removing from the link must be done
3✔
2420
        // in the same block while the mutex is held.
3✔
2421
        close(stopChan)
3✔
2422
        delete(s.linkStopIndex, chanID)
3✔
2423
        s.indexMtx.Unlock()
3✔
2424
}
2425

2426
// removeLink is used to remove and stop the channel link.
2427
//
2428
// NOTE: This MUST be called with the indexMtx held.
2429
func (s *Switch) removeLink(chanID lnwire.ChannelID) ChannelLink {
3✔
2430
        log.Infof("Removing channel link with ChannelID(%v)", chanID)
3✔
2431

3✔
2432
        link, err := s.getLink(chanID)
3✔
2433
        if err != nil {
3✔
2434
                return nil
×
2435
        }
×
2436

2437
        // Remove the channel from live link indexes.
2438
        delete(s.pendingLinkIndex, link.ChanID())
3✔
2439
        delete(s.linkIndex, link.ChanID())
3✔
2440
        delete(s.forwardingIndex, link.ShortChanID())
3✔
2441

3✔
2442
        // If the link has been added to the peer index, then we'll move to
3✔
2443
        // delete the entry within the index.
3✔
2444
        peerPub := link.PeerPubKey()
3✔
2445
        if peerIndex, ok := s.interfaceIndex[peerPub]; ok {
6✔
2446
                delete(peerIndex, link.ChanID())
3✔
2447

3✔
2448
                // If after deletion, there are no longer any links, then we'll
3✔
2449
                // remove the interface map all together.
3✔
2450
                if len(peerIndex) == 0 {
6✔
2451
                        delete(s.interfaceIndex, peerPub)
3✔
2452
                }
3✔
2453
        }
2454

2455
        return link
3✔
2456
}
2457

2458
// UpdateShortChanID locates the link with the passed-in chanID and updates the
2459
// underlying channel state. This is only used in zero-conf channels to allow
2460
// the confirmed SCID to be updated.
2461
func (s *Switch) UpdateShortChanID(chanID lnwire.ChannelID) error {
3✔
2462
        s.indexMtx.Lock()
3✔
2463
        defer s.indexMtx.Unlock()
3✔
2464

3✔
2465
        // Locate the target link in the link index. If no such link exists,
3✔
2466
        // then we will ignore the request.
3✔
2467
        link, ok := s.linkIndex[chanID]
3✔
2468
        if !ok {
3✔
2469
                return fmt.Errorf("link %v not found", chanID)
×
2470
        }
×
2471

2472
        // Try to update the link's underlying channel state, returning early
2473
        // if this update failed.
2474
        _, err := link.UpdateShortChanID()
3✔
2475
        if err != nil {
3✔
2476
                return err
×
2477
        }
×
2478

2479
        // Since the zero-conf channel is confirmed, we should populate the
2480
        // aliasToReal map and update the baseIndex.
2481
        aliases := link.getAliases()
3✔
2482

3✔
2483
        confirmedScid := link.confirmedScid()
3✔
2484

3✔
2485
        for _, alias := range aliases {
6✔
2486
                s.aliasToReal[alias] = confirmedScid
3✔
2487
        }
3✔
2488

2489
        s.baseIndex[confirmedScid] = link.ShortChanID()
3✔
2490

3✔
2491
        return nil
3✔
2492
}
2493

2494
// GetLinksByInterface fetches all the links connected to a particular node
2495
// identified by the serialized compressed form of its public key.
2496
func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
2497
        error) {
3✔
2498

3✔
2499
        s.indexMtx.RLock()
3✔
2500
        defer s.indexMtx.RUnlock()
3✔
2501

3✔
2502
        var handlers []ChannelUpdateHandler
3✔
2503

3✔
2504
        links, err := s.getLinks(hop)
3✔
2505
        if err != nil {
6✔
2506
                return nil, err
3✔
2507
        }
3✔
2508

2509
        // Range over the returned []ChannelLink to convert them into
2510
        // []ChannelUpdateHandler.
2511
        for _, link := range links {
6✔
2512
                handlers = append(handlers, link)
3✔
2513
        }
3✔
2514

2515
        return handlers, nil
3✔
2516
}
2517

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

2528
        channelLinks := make([]ChannelLink, 0, len(links))
3✔
2529
        for _, link := range links {
6✔
2530
                channelLinks = append(channelLinks, link)
3✔
2531
        }
3✔
2532

2533
        return channelLinks, nil
3✔
2534
}
2535

2536
// CircuitModifier returns a reference to subset of the interfaces provided by
2537
// the circuit map, to allow links to open and close circuits.
2538
func (s *Switch) CircuitModifier() CircuitModifier {
3✔
2539
        return s.circuits
3✔
2540
}
3✔
2541

2542
// CircuitLookup returns a reference to subset of the interfaces provided by the
2543
// circuit map, to allow looking up circuits.
2544
func (s *Switch) CircuitLookup() CircuitLookup {
3✔
2545
        return s.circuits
3✔
2546
}
3✔
2547

2548
// commitCircuits persistently adds a circuit to the switch's circuit map.
2549
func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
2550
        *CircuitFwdActions, error) {
×
2551

×
2552
        return s.circuits.CommitCircuits(circuits...)
×
2553
}
×
2554

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

3✔
2564
        // If we won't have any forwarding events, then we can exit early.
3✔
2565
        if len(s.pendingFwdingEvents) == 0 {
6✔
2566
                s.fwdEventMtx.Unlock()
3✔
2567
                return nil
3✔
2568
        }
3✔
2569

2570
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
3✔
2571
        copy(events[:], s.pendingFwdingEvents[:])
3✔
2572

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

3✔
2579
        // Finally, we'll write out the copied events to the persistent
3✔
2580
        // forwarding log.
3✔
2581
        return s.cfg.FwdingLog.AddForwardingEvents(events)
3✔
2582
}
2583

2584
// BestHeight returns the best height known to the switch.
2585
func (s *Switch) BestHeight() uint32 {
3✔
2586
        return atomic.LoadUint32(&s.bestHeight)
3✔
2587
}
3✔
2588

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

3✔
2600
        // Retrieve the link's current commitment feerate and dustClosure.
3✔
2601
        feeRate := link.getFeeRate()
3✔
2602
        isDust := link.getDustClosure()
3✔
2603

3✔
2604
        // Evaluate if the HTLC is dust on either sides' commitment.
3✔
2605
        isLocalDust := isDust(
3✔
2606
                feeRate, incoming, lntypes.Local, amount.ToSatoshis(),
3✔
2607
        )
3✔
2608
        isRemoteDust := isDust(
3✔
2609
                feeRate, incoming, lntypes.Remote, amount.ToSatoshis(),
3✔
2610
        )
3✔
2611

3✔
2612
        if !(isLocalDust || isRemoteDust) {
6✔
2613
                // If the HTLC is not dust on either commitment, it's fine to
3✔
2614
                // forward.
3✔
2615
                return false
3✔
2616
        }
3✔
2617

2618
        // Fetch the dust sums currently in the mailbox for this link.
2619
        cid := link.ChanID()
3✔
2620
        sid := link.ShortChanID()
3✔
2621
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
3✔
2622
        localMailDust, remoteMailDust := mailbox.DustPackets()
3✔
2623

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

3✔
2632
                // Optionally include the HTLC amount only for outgoing
3✔
2633
                // HTLCs.
3✔
2634
                if !incoming {
6✔
2635
                        localSum += amount
3✔
2636
                }
3✔
2637

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

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

3✔
2652
                // Optionally include the HTLC amount only for outgoing
3✔
2653
                // HTLCs.
3✔
2654
                if !incoming {
6✔
2655
                        remoteSum += amount
3✔
2656
                }
3✔
2657

2658
                // Finally check against the defined fee threshold.
2659
                if remoteSum > s.cfg.MaxFeeExposure {
3✔
2660
                        return true
×
2661
                }
×
2662
        }
2663

2664
        // If we reached this point, this HTLC is fine to forward.
2665
        return false
3✔
2666
}
2667

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

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

UNCOV
2691
        return lnwire.NewTemporaryChannelFailure(update)
×
2692
}
2693

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

3✔
2702
        // This function does not defer the unlocking because of the database
3✔
2703
        // lookups for ChannelUpdate.
3✔
2704
        s.indexMtx.RLock()
3✔
2705

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

2723
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2724
                        if err != nil {
×
2725
                                return nil
×
2726
                        }
×
2727

2728
                        // Replace the baseScid with the passed-in alias.
2729
                        update.ShortChannelID = scid
×
2730
                        sig, err := s.cfg.SignAliasUpdate(update)
×
2731
                        if err != nil {
×
2732
                                return nil
×
2733
                        }
×
2734

2735
                        update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2736
                        if err != nil {
×
2737
                                return nil
×
2738
                        }
×
2739

2740
                        return update
×
2741
                }
2742

2743
                s.indexMtx.RUnlock()
3✔
2744

3✔
2745
                // Fetch the SCID via the confirmed SCID and replace it with
3✔
2746
                // the alias.
3✔
2747
                update, err := s.cfg.FetchLastChannelUpdate(realScid)
3✔
2748
                if err != nil {
6✔
2749
                        return nil
3✔
2750
                }
3✔
2751

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

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

2766
                return update
3✔
2767
        }
2768

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

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

2787
        aliases := link.getAliases()
×
2788
        if len(aliases) == 0 {
×
2789
                // This should never happen, but if it does, fallback.
×
2790
                return nil
×
2791
        }
×
2792

2793
        // Fetch the ChannelUpdate via the real, confirmed SCID.
2794
        update, err := s.cfg.FetchLastChannelUpdate(scid)
×
2795
        if err != nil {
×
2796
                return nil
×
2797
        }
×
2798

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

2816
                update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2817
                if err != nil {
×
2818
                        return nil
×
2819
                }
×
2820
        }
2821

2822
        return update
×
2823
}
2824

2825
// AddAliasForLink instructs the Switch to update its in-memory maps to reflect
2826
// that a link has a new alias.
2827
func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
2828
        alias lnwire.ShortChannelID) error {
×
2829

×
2830
        // Fetch the link so that we can update the underlying channel's set of
×
2831
        // aliases.
×
2832
        s.indexMtx.RLock()
×
2833
        link, err := s.getLink(chanID)
×
2834
        s.indexMtx.RUnlock()
×
2835
        if err != nil {
×
2836
                return err
×
2837
        }
×
2838

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

2845
        linkScid := link.ShortChanID()
×
2846

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

×
2855
                        s.aliasToReal[alias] = confirmedScid
×
2856
                }
×
2857

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

2867
        return nil
×
2868
}
2869

2870
// handlePacketAdd handles forwarding an Add packet.
2871
func (s *Switch) handlePacketAdd(packet *htlcPacket,
2872
        htlc *lnwire.UpdateAddHTLC) error {
3✔
2873

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

3✔
2882
                return s.failAddPacket(packet, failure)
3✔
2883
        }
3✔
2884

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

2901
        s.indexMtx.RLock()
3✔
2902
        targetLink, err := s.getLinkByMapping(packet)
3✔
2903
        if err != nil {
6✔
2904
                s.indexMtx.RUnlock()
3✔
2905

3✔
2906
                log.Debugf("unable to find link with "+
3✔
2907
                        "destination %v", packet.outgoingChanID)
3✔
2908

3✔
2909
                // If packet was forwarded from another channel link than we
3✔
2910
                // should notify this link that some error occurred.
3✔
2911
                linkError := NewLinkError(
3✔
2912
                        &lnwire.FailUnknownNextPeer{},
3✔
2913
                )
3✔
2914

3✔
2915
                return s.failAddPacket(packet, linkError)
3✔
2916
        }
3✔
2917
        targetPeerKey := targetLink.PeerPubKey()
3✔
2918
        interfaceLinks, _ := s.getLinks(targetPeerKey)
3✔
2919
        s.indexMtx.RUnlock()
3✔
2920

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

3✔
2927
        // Find all destination channel links with appropriate bandwidth.
3✔
2928
        var destinations []ChannelLink
3✔
2929
        for _, link := range interfaceLinks {
6✔
2930
                var failure *LinkError
3✔
2931

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

2952
                // If this link can forward the htlc, add it to the set of
2953
                // destinations.
2954
                if failure == nil {
6✔
2955
                        destinations = append(destinations, link)
3✔
2956
                        continue
3✔
2957
                }
2958

2959
                linkErrs[link.ShortChanID()] = failure
3✔
2960
        }
2961

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

2983
                log.Tracef("incoming HTLC(%x) violated "+
3✔
2984
                        "target outgoing link (id=%v) policy: %v",
3✔
2985
                        htlc.PaymentHash[:], packet.outgoingChanID,
3✔
2986
                        linkErr)
3✔
2987

3✔
2988
                return s.failAddPacket(packet, linkErr)
3✔
2989
        }
2990

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

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

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

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

×
3023
                return s.failAddPacket(packet, linkErr)
×
3024
        }
×
3025

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

×
3037
                return s.failAddPacket(packet, linkErr)
×
3038
        }
×
3039

3040
        // Send the packet to the destination channel link which manages the
3041
        // channel.
3042
        packet.outgoingChanID = destination.ShortChanID()
3✔
3043

3✔
3044
        return destination.handleSwitchPacket(packet)
3✔
3045
}
3046

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

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

3060
        // Exit early if there's another error.
3061
        if err != nil {
3✔
3062
                return err
×
3063
        }
×
3064

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

3076
        localHTLC := packet.incomingChanID == hop.Source
3✔
3077

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

3✔
3090
                // If this is a locally initiated HTLC, there's no need to
3✔
3091
                // forward it so we exit.
3✔
3092
                return nil
3✔
3093
        }
3✔
3094

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

3✔
3105
                s.fwdEventMtx.Lock()
3✔
3106
                s.pendingFwdingEvents = append(
3✔
3107
                        s.pendingFwdingEvents,
3✔
3108
                        channeldb.ForwardingEvent{
3✔
3109
                                Timestamp:      time.Now(),
3✔
3110
                                IncomingChanID: circuit.Incoming.ChanID,
3✔
3111
                                OutgoingChanID: circuit.Outgoing.ChanID,
3✔
3112
                                AmtIn:          circuit.IncomingAmount,
3✔
3113
                                AmtOut:         circuit.OutgoingAmount,
3✔
3114
                                IncomingHtlcID: fn.Some(
3✔
3115
                                        circuit.Incoming.HtlcID,
3✔
3116
                                ),
3✔
3117
                                OutgoingHtlcID: fn.Some(
3✔
3118
                                        circuit.Outgoing.HtlcID,
3✔
3119
                                ),
3✔
3120
                        },
3✔
3121
                )
3✔
3122
                s.fwdEventMtx.Unlock()
3✔
3123
        }
3✔
3124

3125
        // Deliver this packet.
3126
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3127
}
3128

3129
// handlePacketFail handles forwarding a fail packet.
3130
func (s *Switch) handlePacketFail(packet *htlcPacket,
3131
        htlc *lnwire.UpdateFailHTLC) error {
3✔
3132

3✔
3133
        // If the source of this packet has not been set, use the circuit map
3✔
3134
        // to lookup the origin.
3✔
3135
        circuit, err := s.closeCircuit(packet)
3✔
3136
        if err != nil {
3✔
3137
                return err
×
3138
        }
×
3139

3140
        // If this is a locally initiated HTLC, we need to handle the packet by
3141
        // storing the network result.
3142
        //
3143
        // A blank IncomingChanID in a circuit indicates that it is a pending
3144
        // user-initiated payment.
3145
        //
3146
        // NOTE: `closeCircuit` modifies the state of `packet`.
3147
        if packet.incomingChanID == hop.Source {
6✔
3148
                // TODO(yy): remove the goroutine and send back the error here.
3✔
3149
                s.wg.Add(1)
3✔
3150
                go s.handleLocalResponse(packet)
3✔
3151

3✔
3152
                // If this is a locally initiated HTLC, there's no need to
3✔
3153
                // forward it so we exit.
3✔
3154
                return nil
3✔
3155
        }
3✔
3156

3157
        // Exit early if this hasSource is true. This flag is only set via
3158
        // mailbox's `FailAdd`. This method has two callsites,
3159
        // - the packet has timed out after `MailboxDeliveryTimeout`, defaults
3160
        //   to 1 min.
3161
        // - the HTLC fails the validation in `channel.AddHTLC`.
3162
        // In either case, the `Reason` field is populated. Thus there's no
3163
        // need to proceed and extract the failure reason below.
3164
        if packet.hasSource {
3✔
3165
                // Deliver this packet.
×
3166
                return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
×
3167
        }
×
3168

3169
        // HTLC resolutions and messages restored from disk don't have the
3170
        // obfuscator set from the original htlc add packet - set it here for
3171
        // use in blinded errors.
3172
        packet.obfuscator = circuit.ErrorEncrypter
3✔
3173

3✔
3174
        switch {
3✔
3175
        // No message to encrypt, locally sourced payment.
3176
        case circuit.ErrorEncrypter == nil:
×
3177
                // TODO(yy) further check this case as we shouldn't end up here
3178
                // as `isLocal` is already false.
3179

3180
        // If this is a resolution message, then we'll need to encrypt it as
3181
        // it's actually internally sourced.
3182
        case packet.isResolution:
3✔
3183
                var err error
3✔
3184
                // TODO(roasbeef): don't need to pass actually?
3✔
3185
                failure := &lnwire.FailPermanentChannelFailure{}
3✔
3186
                htlc.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
3✔
3187
                        failure,
3✔
3188
                )
3✔
3189
                if err != nil {
3✔
3190
                        err = fmt.Errorf("unable to obfuscate error: %w", err)
×
3191
                        log.Error(err)
×
3192
                }
×
3193

3194
        // Alternatively, if the remote party sends us an
3195
        // UpdateFailMalformedHTLC, then we'll need to convert this into a
3196
        // proper well formatted onion error as there's no HMAC currently.
3197
        case packet.convertedError:
3✔
3198
                log.Infof("Converting malformed HTLC error for circuit for "+
3✔
3199
                        "Circuit(%x: (%s, %d) <-> (%s, %d))",
3✔
3200
                        packet.circuit.PaymentHash,
3✔
3201
                        packet.incomingChanID, packet.incomingHTLCID,
3✔
3202
                        packet.outgoingChanID, packet.outgoingHTLCID)
3✔
3203

3✔
3204
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
3✔
3205
                        htlc.Reason,
3✔
3206
                )
3✔
3207

3208
        default:
3✔
3209
                // Otherwise, it's a forwarded error, so we'll perform a
3✔
3210
                // wrapper encryption as normal.
3✔
3211
                htlc.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
3✔
3212
                        htlc.Reason,
3✔
3213
                )
3✔
3214
        }
3215

3216
        // Deliver this packet.
3217
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3218
}
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