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

lightningnetwork / lnd / 17257443467

27 Aug 2025 04:37AM UTC coverage: 57.349% (+0.03%) from 57.321%
17257443467

Pull #10049

github

web-flow
Merge cd958d383 into 0c2f045f5
Pull Request #10049: multi: prevent duplicates for locally dispatched HTLC attempts

88 of 123 new or added lines in 4 files covered. (71.54%)

62 existing lines in 14 files now uncovered.

99293 of 173139 relevant lines covered (57.35%)

1.78 hits per line

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

74.11
/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✔
444
                return true, nil
×
445
        }
×
446

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

451
        return false, nil
3✔
452
}
453

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

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

3✔
475
        // If the HTLC is not found in the circuit map, check whether a result
3✔
476
        // is already available.
3✔
477
        // Assumption: no one will add this attempt ID other than the caller.
3✔
478
        if s.circuits.LookupCircuit(inKey) == nil {
3✔
NEW
479
                res, err := s.attemptStore.GetResult(attemptID)
×
480
                if err != nil {
×
481
                        return nil, err
×
482
                }
×
483
                c := make(chan *networkResult, 1)
×
484
                c <- res
×
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✔
731
        case <-linkQuit:
1✔
732
                return nil
1✔
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.
1088
        case unencrypted:
1✔
1089
                r := bytes.NewReader(htlc.Reason)
1✔
1090
                failureMsg, err := lnwire.DecodeFailure(r, 0)
1✔
1091
                if err != nil {
1✔
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.
1110
                return NewLinkError(failureMsg)
1✔
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 {
4✔
1311
                circuit, err := s.circuits.FailCircuit(pkt.inKey())
1✔
1312
                switch err {
1✔
1313

1314
                // Circuit successfully closed.
1315
                case nil:
1✔
1316
                        return circuit, nil
1✔
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
                log.Debugf("Link not found in forwarding index using "+
3✔
2255
                        "chanID=%v", chanID)
3✔
2256

3✔
2257
                return nil, ErrChannelLinkNotFound
3✔
2258
        }
3✔
2259

2260
        return link, nil
3✔
2261
}
2262

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

3✔
2284
        log.Debugf("Querying outgoing link using chanID=%v, aliasID=%v", chanID,
3✔
2285
                aliasID)
3✔
2286

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

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

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

×
2307
                        // Link not found, bail.
×
2308
                        return nil, ErrChannelLinkNotFound
×
2309
                }
×
2310

2311
                // Change the packet's outgoingChanID field so that errors are
2312
                // properly attributed.
2313
                pkt.outgoingChanID = baseScid
3✔
2314

3✔
2315
                // Return the link without checking if it's private or not.
3✔
2316
                return link, nil
3✔
2317
        }
2318

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

3✔
2331
                        // The link wasn't found, bail out.
3✔
2332
                        return nil, ErrChannelLinkNotFound
3✔
2333
                }
3✔
2334

2335
                return link, nil
3✔
2336
        }
2337

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

×
2344
                // Link wasn't found, bail out.
×
2345
                return nil, ErrChannelLinkNotFound
×
2346
        }
×
2347

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

×
2355
                return nil, ErrChannelLinkNotFound
×
2356
        }
×
2357

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

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

3✔
2371
        if link, ok := s.linkIndex[chanID]; ok {
6✔
2372
                return link.EligibleToForward()
3✔
2373
        }
3✔
2374

2375
        return false
3✔
2376
}
2377

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

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

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

2415
        // Stop the link before removing it from the maps.
2416
        link.Stop()
3✔
2417

3✔
2418
        s.indexMtx.Lock()
3✔
2419
        _ = s.removeLink(chanID)
3✔
2420

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

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

3✔
2435
        link, err := s.getLink(chanID)
3✔
2436
        if err != nil {
3✔
2437
                return nil
×
2438
        }
×
2439

2440
        // Remove the channel from live link indexes.
2441
        delete(s.pendingLinkIndex, link.ChanID())
3✔
2442
        delete(s.linkIndex, link.ChanID())
3✔
2443
        delete(s.forwardingIndex, link.ShortChanID())
3✔
2444

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

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

2458
        return link
3✔
2459
}
2460

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

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

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

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

3✔
2486
        confirmedScid := link.confirmedScid()
3✔
2487

3✔
2488
        for _, alias := range aliases {
6✔
2489
                s.aliasToReal[alias] = confirmedScid
3✔
2490
        }
3✔
2491

2492
        s.baseIndex[confirmedScid] = link.ShortChanID()
3✔
2493

3✔
2494
        return nil
3✔
2495
}
2496

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

3✔
2502
        s.indexMtx.RLock()
3✔
2503
        defer s.indexMtx.RUnlock()
3✔
2504

3✔
2505
        var handlers []ChannelUpdateHandler
3✔
2506

3✔
2507
        links, err := s.getLinks(hop)
3✔
2508
        if err != nil {
6✔
2509
                return nil, err
3✔
2510
        }
3✔
2511

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

2518
        return handlers, nil
3✔
2519
}
2520

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

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

2536
        return channelLinks, nil
3✔
2537
}
2538

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

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

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

×
2555
        return s.circuits.CommitCircuits(circuits...)
×
2556
}
×
2557

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

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

2573
        events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
3✔
2574
        copy(events[:], s.pendingFwdingEvents[:])
3✔
2575

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

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

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

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

3✔
2603
        // Retrieve the link's current commitment feerate and dustClosure.
3✔
2604
        feeRate := link.getFeeRate()
3✔
2605
        isDust := link.getDustClosure()
3✔
2606

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

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

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

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

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

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

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

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

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

2667
        // If we reached this point, this HTLC is fine to forward.
2668
        return false
3✔
2669
}
2670

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

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

2694
        return lnwire.NewTemporaryChannelFailure(update)
1✔
2695
}
2696

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

3✔
2705
        // This function does not defer the unlocking because of the database
3✔
2706
        // lookups for ChannelUpdate.
3✔
2707
        s.indexMtx.RLock()
3✔
2708

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

2726
                        update, err := s.cfg.FetchLastChannelUpdate(baseScid)
×
2727
                        if err != nil {
×
2728
                                return nil
×
2729
                        }
×
2730

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

2738
                        update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2739
                        if err != nil {
×
2740
                                return nil
×
2741
                        }
×
2742

2743
                        return update
×
2744
                }
2745

2746
                s.indexMtx.RUnlock()
3✔
2747

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

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

2764
                update.Signature, err = lnwire.NewSigFromSignature(sig)
3✔
2765
                if err != nil {
3✔
2766
                        return nil
×
2767
                }
×
2768

2769
                return update
3✔
2770
        }
2771

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

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

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

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

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

2819
                update.Signature, err = lnwire.NewSigFromSignature(sig)
×
2820
                if err != nil {
×
2821
                        return nil
×
2822
                }
×
2823
        }
2824

2825
        return update
×
2826
}
2827

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

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

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

2848
        linkScid := link.ShortChanID()
×
2849

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

×
2858
                        s.aliasToReal[alias] = confirmedScid
×
2859
                }
×
2860

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

2870
        return nil
×
2871
}
2872

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

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

3✔
2885
                return s.failAddPacket(packet, failure)
3✔
2886
        }
3✔
2887

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

2904
        s.indexMtx.RLock()
3✔
2905
        targetLink, err := s.getLinkByMapping(packet)
3✔
2906
        if err != nil {
6✔
2907
                s.indexMtx.RUnlock()
3✔
2908

3✔
2909
                log.Debugf("unable to find link with "+
3✔
2910
                        "destination %v", packet.outgoingChanID)
3✔
2911

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

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

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

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

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

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

2962
                linkErrs[link.ShortChanID()] = failure
3✔
2963
        }
2964

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

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

3✔
2991
                return s.failAddPacket(packet, linkErr)
3✔
2992
        }
2993

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

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

×
3012
                return s.failAddPacket(packet, linkErr)
×
3013
        }
×
3014

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

×
3026
                return s.failAddPacket(packet, linkErr)
×
3027
        }
×
3028

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

×
3040
                return s.failAddPacket(packet, linkErr)
×
3041
        }
×
3042

3043
        // Send the packet to the destination channel link which manages the
3044
        // channel.
3045
        packet.outgoingChanID = destination.ShortChanID()
3✔
3046

3✔
3047
        return destination.handleSwitchPacket(packet)
3✔
3048
}
3049

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

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

3063
        // Exit early if there's another error.
3064
        if err != nil {
3✔
3065
                return err
×
3066
        }
×
3067

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

3079
        localHTLC := packet.incomingChanID == hop.Source
3✔
3080

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

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

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

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

3128
        // Deliver this packet.
3129
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3130
}
3131

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

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

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

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

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

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

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

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

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

3✔
3207
                htlc.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
3✔
3208
                        htlc.Reason,
3✔
3209
                )
3✔
3210

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

3219
        // Deliver this packet.
3220
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
3✔
3221
}
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