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

lightningnetwork / lnd / 16673052227

01 Aug 2025 10:44AM UTC coverage: 67.016% (-0.03%) from 67.047%
16673052227

Pull #9888

github

web-flow
Merge 1dd8765d7 into 37523b6cb
Pull Request #9888: Attributable failures

325 of 384 new or added lines in 16 files covered. (84.64%)

131 existing lines in 24 files now uncovered.

135611 of 202355 relevant lines covered (67.02%)

21613.83 hits per line

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

82.16
/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
        // ExtractSharedSecret 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
        ExtractSharedSecret hop.SharedSecretGenerator
174

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
        errChan chan error
412
}
413

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

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

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

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

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

451
        return false, nil
3✔
452
}
453

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

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

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

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

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

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

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

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

533
        return resultChan, nil
303✔
534
}
535

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

823
        return nil
88✔
824
}
825

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

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

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

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

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

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

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

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

899
                // The base SCID was found, so we'll use that to fetch the
900
                // link.
901
                link, err = s.getLinkByShortID(baseScid)
4✔
902
                if err != nil {
4✔
903
                        s.indexMtx.RUnlock()
×
904
                        log.Errorf("Link %v not found", baseScid)
×
905
                        return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
×
906
                }
×
907
        }
908
        // We finished looking up the indexes, so we can unlock the mutex before
909
        // performing the link operations which might also acquire the lock
910
        // in case e.g. failAliasUpdate is called.
911
        s.indexMtx.RUnlock()
415✔
912

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

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

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

937
        return link, nil
411✔
938
}
939

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

122✔
1061
        switch {
122✔
1062

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

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

×
1084
                        return linkError
×
1085
                }
×
1086

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

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

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

3✔
1104
                return linkError
3✔
1105

1106
        // A regular multi-hop payment error that we'll need to
1107
        // decrypt.
1108
        default:
120✔
1109
                attrData, err := lnwire.ExtraDataToAttrData(htlc.ExtraData)
120✔
1110
                if err != nil {
120✔
NEW
1111
                        return err
×
NEW
1112
                }
×
1113

1114
                // We'll attempt to fully decrypt the onion encrypted
1115
                // error. If we're unable to then we'll bail early.
1116
                failure, err := deobfuscator.DecryptError(htlc.Reason, attrData)
120✔
1117
                if err != nil {
121✔
1118
                        log.Errorf("unable to de-obfuscate onion failure "+
1✔
1119
                                "(hash=%v, pid=%d): %v",
1✔
1120
                                paymentHash, attemptID, err)
1✔
1121

1✔
1122
                        return ErrUnreadableFailureMessage
1✔
1123
                }
1✔
1124

1125
                return failure
119✔
1126
        }
1127
}
1128

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

1140
        case *lnwire.UpdateFulfillHTLC:
402✔
1141
                return s.handlePacketSettle(packet)
402✔
1142

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

1152
        default:
×
1153
                return fmt.Errorf("wrong update type: %T", htlc)
×
1154
        }
1155
}
1156

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

92✔
1163
        log.Tracef("Checking for circular route: incoming=%v, outgoing=%v "+
92✔
1164
                "(payment hash: %x)", incoming, outgoing, paymentHash[:])
92✔
1165

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

1176
                // Otherwise, we'll return a temporary channel failure.
1177
                return NewDetailedLinkError(
2✔
1178
                        lnwire.NewTemporaryChannelFailure(nil),
2✔
1179
                        OutgoingFailureCircularRoute,
2✔
1180
                )
2✔
1181
        }
1182

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

1196
        outgoingBaseScid, ok := s.baseIndex[outgoing]
9✔
1197
        if !ok {
14✔
1198
                // This channel does not use baseIndex, bail out.
5✔
1199
                s.indexMtx.RUnlock()
5✔
1200
                return nil
5✔
1201
        }
5✔
1202
        s.indexMtx.RUnlock()
7✔
1203

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

3✔
1210
                // The base SCIDs are not equal so these are not the same
3✔
1211
                // channel.
3✔
1212
                return nil
3✔
1213
        }
3✔
1214

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

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

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

1251
        log.Error(failure.Error())
29✔
1252

29✔
1253
        extraData, err := lnwire.AttrDataToExtraData(attrData)
29✔
1254
        if err != nil {
29✔
NEW
1255
                return err
×
NEW
1256
        }
×
1257

1258
        // Create a failure packet for this htlc. The full set of
1259
        // information about the htlc failure is included so that they can
1260
        // be included in link failure notifications.
1261
        failPkt := &htlcPacket{
29✔
1262
                sourceRef:       packet.sourceRef,
29✔
1263
                incomingChanID:  packet.incomingChanID,
29✔
1264
                incomingHTLCID:  packet.incomingHTLCID,
29✔
1265
                outgoingChanID:  packet.outgoingChanID,
29✔
1266
                outgoingHTLCID:  packet.outgoingHTLCID,
29✔
1267
                incomingAmount:  packet.incomingAmount,
29✔
1268
                amount:          packet.amount,
29✔
1269
                incomingTimeout: packet.incomingTimeout,
29✔
1270
                outgoingTimeout: packet.outgoingTimeout,
29✔
1271
                circuit:         packet.circuit,
29✔
1272
                obfuscator:      packet.obfuscator,
29✔
1273
                linkFailure:     failure,
29✔
1274
                htlc: &lnwire.UpdateFailHTLC{
29✔
1275
                        Reason:    reason,
29✔
1276
                        ExtraData: extraData,
29✔
1277
                },
29✔
1278
        }
29✔
1279

29✔
1280
        // Route a fail packet back to the source link.
29✔
1281
        err = s.mailOrchestrator.Deliver(failPkt.incomingChanID, failPkt)
29✔
1282
        if err != nil {
29✔
1283
                err = fmt.Errorf("source chanid=%v unable to "+
×
1284
                        "handle switch packet: %v",
×
1285
                        packet.incomingChanID, err)
×
1286
                log.Error(err)
×
1287
                return err
×
1288
        }
×
1289

1290
        return failure
29✔
1291
}
1292

1293
// closeCircuit accepts a settle or fail htlc and the associated htlc packet and
1294
// attempts to determine the source that forwarded this htlc. This method will
1295
// set the incoming chan and htlc ID of the given packet if the source was
1296
// found, and will properly [re]encrypt any failure messages.
1297
func (s *Switch) closeCircuit(pkt *htlcPacket) (*PaymentCircuit, error) {
535✔
1298
        // If the packet has its source, that means it was failed locally by
535✔
1299
        // the outgoing link. We fail it here to make sure only one response
535✔
1300
        // makes it through the switch.
535✔
1301
        if pkt.hasSource {
545✔
1302
                circuit, err := s.circuits.FailCircuit(pkt.inKey())
10✔
1303
                switch err {
10✔
1304

1305
                // Circuit successfully closed.
1306
                case nil:
10✔
1307
                        return circuit, nil
10✔
1308

1309
                // Circuit was previously closed, but has not been deleted.
1310
                // We'll just drop this response until the circuit has been
1311
                // fully removed.
1312
                case ErrCircuitClosing:
×
1313
                        return nil, err
×
1314

1315
                // Failed to close circuit because it does not exist. This is
1316
                // likely because the circuit was already successfully closed.
1317
                // Since this packet failed locally, there is no forwarding
1318
                // package entry to acknowledge.
1319
                case ErrUnknownCircuit:
×
1320
                        return nil, err
×
1321

1322
                // Unexpected error.
1323
                default:
×
1324
                        return nil, err
×
1325
                }
1326
        }
1327

1328
        // Otherwise, this is packet was received from the remote party.  Use
1329
        // circuit map to find the incoming link to receive the settle/fail.
1330
        circuit, err := s.circuits.CloseCircuit(pkt.outKey())
528✔
1331
        switch err {
528✔
1332

1333
        // Open circuit successfully closed.
1334
        case nil:
338✔
1335
                pkt.incomingChanID = circuit.Incoming.ChanID
338✔
1336
                pkt.incomingHTLCID = circuit.Incoming.HtlcID
338✔
1337
                pkt.circuit = circuit
338✔
1338
                pkt.sourceRef = &circuit.AddRef
338✔
1339

338✔
1340
                pktType := "SETTLE"
338✔
1341
                if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
467✔
1342
                        pktType = "FAIL"
129✔
1343
                }
129✔
1344

1345
                log.Debugf("Closed completed %s circuit for %x: "+
338✔
1346
                        "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
338✔
1347
                        pkt.incomingChanID, pkt.incomingHTLCID,
338✔
1348
                        pkt.outgoingChanID, pkt.outgoingHTLCID)
338✔
1349

338✔
1350
                return circuit, nil
338✔
1351

1352
        // Circuit was previously closed, but has not been deleted. We'll just
1353
        // drop this response until the circuit has been removed.
1354
        case ErrCircuitClosing:
3✔
1355
                return nil, err
3✔
1356

1357
        // Failed to close circuit because it does not exist. This is likely
1358
        // because the circuit was already successfully closed.
1359
        case ErrUnknownCircuit:
193✔
1360
                if pkt.destRef != nil {
385✔
1361
                        // Add this SettleFailRef to the set of pending settle/fail entries
192✔
1362
                        // awaiting acknowledgement.
192✔
1363
                        s.pendingSettleFails = append(s.pendingSettleFails, *pkt.destRef)
192✔
1364
                }
192✔
1365

1366
                // If this is a settle, we will not log an error message as settles
1367
                // are expected to hit the ErrUnknownCircuit case. The only way fails
1368
                // can hit this case if the link restarts after having just sent a fail
1369
                // to the switch.
1370
                _, isSettle := pkt.htlc.(*lnwire.UpdateFulfillHTLC)
193✔
1371
                if !isSettle {
193✔
1372
                        err := fmt.Errorf("unable to find target channel "+
×
1373
                                "for HTLC fail: channel ID = %s, "+
×
1374
                                "HTLC ID = %d", pkt.outgoingChanID,
×
1375
                                pkt.outgoingHTLCID)
×
1376
                        log.Error(err)
×
1377

×
1378
                        return nil, err
×
1379
                }
×
1380

1381
                return nil, nil
193✔
1382

1383
        // Unexpected error.
1384
        default:
×
1385
                return nil, err
×
1386
        }
1387
}
1388

1389
// ackSettleFail is used by the switch to ACK any settle/fail entries in the
1390
// forwarding package of the outgoing link for a payment circuit. We do this if
1391
// we're the originator of the payment, so the link stops attempting to
1392
// re-broadcast.
1393
func (s *Switch) ackSettleFail(settleFailRefs ...channeldb.SettleFailRef) error {
120✔
1394
        return kvdb.Batch(s.cfg.DB, func(tx kvdb.RwTx) error {
240✔
1395
                return s.cfg.SwitchPackager.AckSettleFails(tx, settleFailRefs...)
120✔
1396
        })
120✔
1397
}
1398

1399
// teardownCircuit removes a pending or open circuit from the switch's circuit
1400
// map and prints useful logging statements regarding the outcome.
1401
func (s *Switch) teardownCircuit(pkt *htlcPacket) error {
313✔
1402
        var pktType string
313✔
1403
        switch htlc := pkt.htlc.(type) {
313✔
1404
        case *lnwire.UpdateFulfillHTLC:
189✔
1405
                pktType = "SETTLE"
189✔
1406
        case *lnwire.UpdateFailHTLC:
127✔
1407
                pktType = "FAIL"
127✔
1408
        default:
×
1409
                return fmt.Errorf("cannot tear down packet of type: %T", htlc)
×
1410
        }
1411

1412
        var paymentHash lntypes.Hash
313✔
1413

313✔
1414
        // Perform a defensive check to make sure we don't try to access a nil
313✔
1415
        // circuit.
313✔
1416
        circuit := pkt.circuit
313✔
1417
        if circuit != nil {
626✔
1418
                copy(paymentHash[:], circuit.PaymentHash[:])
313✔
1419
        }
313✔
1420

1421
        log.Debugf("Tearing down circuit with %s pkt, removing circuit=%v "+
313✔
1422
                "with keystone=%v", pktType, pkt.inKey(), pkt.outKey())
313✔
1423

313✔
1424
        err := s.circuits.DeleteCircuits(pkt.inKey())
313✔
1425
        if err != nil {
313✔
1426
                log.Warnf("Failed to tear down circuit (%s, %d) <-> (%s, %d) "+
×
1427
                        "with payment_hash=%v using %s pkt", pkt.incomingChanID,
×
1428
                        pkt.incomingHTLCID, pkt.outgoingChanID,
×
1429
                        pkt.outgoingHTLCID, pkt.circuit.PaymentHash, pktType)
×
1430

×
1431
                return err
×
1432
        }
×
1433

1434
        log.Debugf("Closed %s circuit for %v: (%s, %d) <-> (%s, %d)", pktType,
313✔
1435
                paymentHash, pkt.incomingChanID, pkt.incomingHTLCID,
313✔
1436
                pkt.outgoingChanID, pkt.outgoingHTLCID)
313✔
1437

313✔
1438
        return nil
313✔
1439
}
1440

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

3✔
1451
        // TODO(roasbeef) abstract out the close updates.
3✔
1452
        updateChan := make(chan interface{}, 2)
3✔
1453
        errChan := make(chan error, 1)
3✔
1454

3✔
1455
        command := &ChanClose{
3✔
1456
                CloseType:      closeType,
3✔
1457
                ChanPoint:      chanPoint,
3✔
1458
                Updates:        updateChan,
3✔
1459
                TargetFeePerKw: targetFeePerKw,
3✔
1460
                DeliveryScript: deliveryScript,
3✔
1461
                Err:            errChan,
3✔
1462
                MaxFee:         maxFee,
3✔
1463
                Ctx:            ctx,
3✔
1464
        }
3✔
1465

3✔
1466
        select {
3✔
1467
        case s.chanCloseRequests <- command:
3✔
1468
                return updateChan, errChan
3✔
1469

1470
        case <-s.quit:
×
1471
                errChan <- ErrSwitchExiting
×
1472
                close(updateChan)
×
1473
                return updateChan, errChan
×
1474
        }
1475
}
1476

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

210✔
1490
        defer func() {
420✔
1491
                s.blockEpochStream.Cancel()
210✔
1492

210✔
1493
                // Remove all links once we've been signalled for shutdown.
210✔
1494
                var linksToStop []ChannelLink
210✔
1495
                s.indexMtx.Lock()
210✔
1496
                for _, link := range s.linkIndex {
505✔
1497
                        activeLink := s.removeLink(link.ChanID())
295✔
1498
                        if activeLink == nil {
295✔
1499
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1500
                                        "on stop", link.ChanID())
×
1501
                                continue
×
1502
                        }
1503
                        linksToStop = append(linksToStop, activeLink)
295✔
1504
                }
1505
                for _, link := range s.pendingLinkIndex {
214✔
1506
                        pendingLink := s.removeLink(link.ChanID())
4✔
1507
                        if pendingLink == nil {
4✔
1508
                                log.Errorf("unable to remove ChannelLink(%v) "+
×
1509
                                        "on stop", link.ChanID())
×
1510
                                continue
×
1511
                        }
1512
                        linksToStop = append(linksToStop, pendingLink)
4✔
1513
                }
1514
                s.indexMtx.Unlock()
210✔
1515

210✔
1516
                // Now that all pending and live links have been removed from
210✔
1517
                // the forwarding indexes, stop each one before shutting down.
210✔
1518
                // We'll shut them down in parallel to make exiting as fast as
210✔
1519
                // possible.
210✔
1520
                var wg sync.WaitGroup
210✔
1521
                for _, link := range linksToStop {
506✔
1522
                        wg.Add(1)
296✔
1523
                        go func(l ChannelLink) {
592✔
1524
                                defer wg.Done()
296✔
1525

296✔
1526
                                l.Stop()
296✔
1527
                        }(link)
296✔
1528
                }
1529
                wg.Wait()
210✔
1530

210✔
1531
                // Before we exit fully, we'll attempt to flush out any
210✔
1532
                // forwarding events that may still be lingering since the last
210✔
1533
                // batch flush.
210✔
1534
                if err := s.FlushForwardingEvents(); err != nil {
210✔
1535
                        log.Errorf("unable to flush forwarding events: %v", err)
×
1536
                }
×
1537
        }()
1538

1539
        // TODO(roasbeef): cleared vs settled distinction
1540
        var (
210✔
1541
                totalNumUpdates uint64
210✔
1542
                totalSatSent    btcutil.Amount
210✔
1543
                totalSatRecv    btcutil.Amount
210✔
1544
        )
210✔
1545
        s.cfg.LogEventTicker.Resume()
210✔
1546
        defer s.cfg.LogEventTicker.Stop()
210✔
1547

210✔
1548
        // Every 15 seconds, we'll flush out the forwarding events that
210✔
1549
        // occurred during that period.
210✔
1550
        s.cfg.FwdEventTicker.Resume()
210✔
1551
        defer s.cfg.FwdEventTicker.Stop()
210✔
1552

210✔
1553
        defer s.cfg.AckEventTicker.Stop()
210✔
1554

210✔
1555
out:
210✔
1556
        for {
1,039✔
1557

829✔
1558
                // If the set of pending settle/fail entries is non-zero,
829✔
1559
                // reinstate the ack ticker so we can batch ack them.
829✔
1560
                if len(s.pendingSettleFails) > 0 {
1,209✔
1561
                        s.cfg.AckEventTicker.Resume()
380✔
1562
                }
380✔
1563

1564
                select {
829✔
1565
                case blockEpoch, ok := <-s.blockEpochStream.Epochs:
3✔
1566
                        if !ok {
3✔
1567
                                break out
×
1568
                        }
1569

1570
                        atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
3✔
1571

1572
                // A local close request has arrived, we'll forward this to the
1573
                // relevant link (if it exists) so the channel can be
1574
                // cooperatively closed (if possible).
1575
                case req := <-s.chanCloseRequests:
3✔
1576
                        chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
3✔
1577

3✔
1578
                        s.indexMtx.RLock()
3✔
1579
                        link, ok := s.linkIndex[chanID]
3✔
1580
                        if !ok {
6✔
1581
                                s.indexMtx.RUnlock()
3✔
1582

3✔
1583
                                req.Err <- fmt.Errorf("no peer for channel with "+
3✔
1584
                                        "chan_id=%x", chanID[:])
3✔
1585
                                continue
3✔
1586
                        }
1587
                        s.indexMtx.RUnlock()
3✔
1588

3✔
1589
                        peerPub := link.PeerPubKey()
3✔
1590
                        log.Debugf("Requesting local channel close: peer=%x, "+
3✔
1591
                                "chan_id=%x", link.PeerPubKey(), chanID[:])
3✔
1592

3✔
1593
                        go s.cfg.LocalChannelClose(peerPub[:], req)
3✔
1594

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

1612
                        // At this point, the resolution message has been
1613
                        // persisted. It is safe to signal success by sending
1614
                        // a nil error since the Switch will re-deliver the
1615
                        // resolution message on restart.
1616
                        resolutionMsg.errChan <- nil
4✔
1617

4✔
1618
                        // Create a htlc packet for this resolution. We do
4✔
1619
                        // not have some of the information that we'll need
4✔
1620
                        // for blinded error handling here , so we'll rely on
4✔
1621
                        // our forwarding logic to fill it in later.
4✔
1622
                        pkt := &htlcPacket{
4✔
1623
                                outgoingChanID: resolutionMsg.SourceChan,
4✔
1624
                                outgoingHTLCID: resolutionMsg.HtlcIndex,
4✔
1625
                                isResolution:   true,
4✔
1626
                        }
4✔
1627

4✔
1628
                        // Resolution messages will either be cancelling
4✔
1629
                        // backwards an existing HTLC, or settling a previously
4✔
1630
                        // outgoing HTLC. Based on this, we'll map the message
4✔
1631
                        // to the proper htlcPacket.
4✔
1632
                        if resolutionMsg.Failure != nil {
7✔
1633
                                pkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1634
                        } else {
7✔
1635
                                pkt.htlc = &lnwire.UpdateFulfillHTLC{
4✔
1636
                                        PaymentPreimage: *resolutionMsg.PreImage,
4✔
1637
                                }
4✔
1638
                        }
4✔
1639

1640
                        log.Debugf("Received outside contract resolution, "+
4✔
1641
                                "mapping to: %v", spew.Sdump(pkt))
4✔
1642

4✔
1643
                        // We don't check the error, as the only failure we can
4✔
1644
                        // encounter is due to the circuit already being
4✔
1645
                        // closed. This is fine, as processing this message is
4✔
1646
                        // meant to be idempotent.
4✔
1647
                        err = s.handlePacketForward(pkt)
4✔
1648
                        if err != nil {
4✔
1649
                                log.Errorf("Unable to forward resolution msg: %v", err)
×
1650
                        }
×
1651

1652
                // A new packet has arrived for forwarding, we'll interpret the
1653
                // packet concretely, then either forward it along, or
1654
                // interpret a return packet to a locally initialized one.
1655
                case cmd := <-s.htlcPlex:
615✔
1656
                        cmd.err <- s.handlePacketForward(cmd.pkt)
615✔
1657

1658
                // When this time ticks, then it indicates that we should
1659
                // collect all the forwarding events since the last internal,
1660
                // and write them out to our log.
1661
                case <-s.cfg.FwdEventTicker.Ticks():
5✔
1662
                        s.wg.Add(1)
5✔
1663
                        go func() {
10✔
1664
                                defer s.wg.Done()
5✔
1665

5✔
1666
                                if err := s.FlushForwardingEvents(); err != nil {
5✔
1667
                                        log.Errorf("Unable to flush "+
×
1668
                                                "forwarding events: %v", err)
×
1669
                                }
×
1670
                        }()
1671

1672
                // The log ticker has fired, so we'll calculate some forwarding
1673
                // stats for the last 10 seconds to display within the logs to
1674
                // users.
1675
                case <-s.cfg.LogEventTicker.Ticks():
7✔
1676
                        // First, we'll collate the current running tally of
7✔
1677
                        // our forwarding stats.
7✔
1678
                        prevSatSent := totalSatSent
7✔
1679
                        prevSatRecv := totalSatRecv
7✔
1680
                        prevNumUpdates := totalNumUpdates
7✔
1681

7✔
1682
                        var (
7✔
1683
                                newNumUpdates uint64
7✔
1684
                                newSatSent    btcutil.Amount
7✔
1685
                                newSatRecv    btcutil.Amount
7✔
1686
                        )
7✔
1687

7✔
1688
                        // Next, we'll run through all the registered links and
7✔
1689
                        // compute their up-to-date forwarding stats.
7✔
1690
                        s.indexMtx.RLock()
7✔
1691
                        for _, link := range s.linkIndex {
16✔
1692
                                // TODO(roasbeef): when links first registered
9✔
1693
                                // stats printed.
9✔
1694
                                updates, sent, recv := link.Stats()
9✔
1695
                                newNumUpdates += updates
9✔
1696
                                newSatSent += sent.ToSatoshis()
9✔
1697
                                newSatRecv += recv.ToSatoshis()
9✔
1698
                        }
9✔
1699
                        s.indexMtx.RUnlock()
7✔
1700

7✔
1701
                        var (
7✔
1702
                                diffNumUpdates uint64
7✔
1703
                                diffSatSent    btcutil.Amount
7✔
1704
                                diffSatRecv    btcutil.Amount
7✔
1705
                        )
7✔
1706

7✔
1707
                        // If this is the first time we're computing these
7✔
1708
                        // stats, then the diff is just the new value. We do
7✔
1709
                        // this in order to avoid integer underflow issues.
7✔
1710
                        if prevNumUpdates == 0 {
14✔
1711
                                diffNumUpdates = newNumUpdates
7✔
1712
                                diffSatSent = newSatSent
7✔
1713
                                diffSatRecv = newSatRecv
7✔
1714
                        } else {
10✔
1715
                                diffNumUpdates = newNumUpdates - prevNumUpdates
3✔
1716
                                diffSatSent = newSatSent - prevSatSent
3✔
1717
                                diffSatRecv = newSatRecv - prevSatRecv
3✔
1718
                        }
3✔
1719

1720
                        // If the diff of num updates is zero, then we haven't
1721
                        // forwarded anything in the last 10 seconds, so we can
1722
                        // skip this update.
1723
                        if diffNumUpdates == 0 {
12✔
1724
                                continue
5✔
1725
                        }
1726

1727
                        // If the diff of num updates is negative, then some
1728
                        // links may have been unregistered from the switch, so
1729
                        // we'll update our stats to only include our registered
1730
                        // links.
1731
                        if int64(diffNumUpdates) < 0 {
8✔
1732
                                totalNumUpdates = newNumUpdates
3✔
1733
                                totalSatSent = newSatSent
3✔
1734
                                totalSatRecv = newSatRecv
3✔
1735
                                continue
3✔
1736
                        }
1737

1738
                        // Otherwise, we'll log this diff, then accumulate the
1739
                        // new stats into the running total.
1740
                        log.Debugf("Sent %d satoshis and received %d satoshis "+
5✔
1741
                                "in the last 10 seconds (%f tx/sec)",
5✔
1742
                                diffSatSent, diffSatRecv,
5✔
1743
                                float64(diffNumUpdates)/10)
5✔
1744

5✔
1745
                        totalNumUpdates += diffNumUpdates
5✔
1746
                        totalSatSent += diffSatSent
5✔
1747
                        totalSatRecv += diffSatRecv
5✔
1748

1749
                // The ack ticker has fired so if we have any settle/fail entries
1750
                // for a forwarding package to ack, we will do so here in a batch
1751
                // db call.
1752
                case <-s.cfg.AckEventTicker.Ticks():
3✔
1753
                        // If the current set is empty, pause the ticker.
3✔
1754
                        if len(s.pendingSettleFails) == 0 {
6✔
1755
                                s.cfg.AckEventTicker.Pause()
3✔
1756
                                continue
3✔
1757
                        }
1758

1759
                        // Batch ack the settle/fail entries.
1760
                        if err := s.ackSettleFail(s.pendingSettleFails...); err != nil {
3✔
1761
                                log.Errorf("Unable to ack batch of settle/fails: %v", err)
×
1762
                                continue
×
1763
                        }
1764

1765
                        log.Tracef("Acked %d settle fails: %v",
3✔
1766
                                len(s.pendingSettleFails),
3✔
1767
                                lnutils.SpewLogClosure(s.pendingSettleFails))
3✔
1768

3✔
1769
                        // Reset the pendingSettleFails buffer while keeping acquired
3✔
1770
                        // memory.
3✔
1771
                        s.pendingSettleFails = s.pendingSettleFails[:0]
3✔
1772

1773
                case <-s.quit:
210✔
1774
                        return
210✔
1775
                }
1776
        }
1777
}
1778

1779
// Start starts all helper goroutines required for the operation of the switch.
1780
func (s *Switch) Start() error {
210✔
1781
        if !atomic.CompareAndSwapInt32(&s.started, 0, 1) {
210✔
1782
                log.Warn("Htlc Switch already started")
×
1783
                return errors.New("htlc switch already started")
×
1784
        }
×
1785

1786
        log.Infof("HTLC Switch starting")
210✔
1787

210✔
1788
        blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
210✔
1789
        if err != nil {
210✔
1790
                return err
×
1791
        }
×
1792
        s.blockEpochStream = blockEpochStream
210✔
1793

210✔
1794
        s.wg.Add(1)
210✔
1795
        go s.htlcForwarder()
210✔
1796

210✔
1797
        if err := s.reforwardResponses(); err != nil {
210✔
1798
                s.Stop()
×
1799
                log.Errorf("unable to reforward responses: %v", err)
×
1800
                return err
×
1801
        }
×
1802

1803
        if err := s.reforwardResolutions(); err != nil {
210✔
1804
                // We are already stopping so we can ignore the error.
×
1805
                _ = s.Stop()
×
1806
                log.Errorf("unable to reforward resolutions: %v", err)
×
1807
                return err
×
1808
        }
×
1809

1810
        return nil
210✔
1811
}
1812

1813
// reforwardResolutions fetches the set of resolution messages stored on-disk
1814
// and reforwards them if their circuits are still open. If the circuits have
1815
// been deleted, then we will delete the resolution message from the database.
1816
func (s *Switch) reforwardResolutions() error {
210✔
1817
        // Fetch all stored resolution messages, deleting the ones that are
210✔
1818
        // resolved.
210✔
1819
        resMsgs, err := s.resMsgStore.fetchAllResolutionMsg()
210✔
1820
        if err != nil {
210✔
1821
                return err
×
1822
        }
×
1823

1824
        switchPackets := make([]*htlcPacket, 0, len(resMsgs))
210✔
1825
        for _, resMsg := range resMsgs {
214✔
1826
                // If the open circuit no longer exists, then we can remove the
4✔
1827
                // message from the store.
4✔
1828
                outKey := CircuitKey{
4✔
1829
                        ChanID: resMsg.SourceChan,
4✔
1830
                        HtlcID: resMsg.HtlcIndex,
4✔
1831
                }
4✔
1832

4✔
1833
                if s.circuits.LookupOpenCircuit(outKey) == nil {
8✔
1834
                        // The open circuit doesn't exist.
4✔
1835
                        err := s.resMsgStore.deleteResolutionMsg(&outKey)
4✔
1836
                        if err != nil {
4✔
1837
                                return err
×
1838
                        }
×
1839

1840
                        continue
4✔
1841
                }
1842

1843
                // The circuit is still open, so we can assume that the link or
1844
                // switch (if we are the source) hasn't cleaned it up yet.
1845
                // We rely on our forwarding logic to fill in details that
1846
                // are not currently available to us.
1847
                resPkt := &htlcPacket{
3✔
1848
                        outgoingChanID: resMsg.SourceChan,
3✔
1849
                        outgoingHTLCID: resMsg.HtlcIndex,
3✔
1850
                        isResolution:   true,
3✔
1851
                }
3✔
1852

3✔
1853
                if resMsg.Failure != nil {
6✔
1854
                        resPkt.htlc = &lnwire.UpdateFailHTLC{}
3✔
1855
                } else {
3✔
1856
                        resPkt.htlc = &lnwire.UpdateFulfillHTLC{
×
1857
                                PaymentPreimage: *resMsg.PreImage,
×
1858
                        }
×
1859
                }
×
1860

1861
                switchPackets = append(switchPackets, resPkt)
3✔
1862
        }
1863

1864
        // We'll now dispatch the set of resolution messages to the proper
1865
        // destination. An error is only encountered here if the switch is
1866
        // shutting down.
1867
        if err := s.ForwardPackets(nil, switchPackets...); err != nil {
210✔
1868
                return err
×
1869
        }
×
1870

1871
        return nil
210✔
1872
}
1873

1874
// reforwardResponses for every known, non-pending channel, loads all associated
1875
// forwarding packages and reforwards any Settle or Fail HTLCs found. This is
1876
// used to resurrect the switch's mailboxes after a restart. This also runs for
1877
// waiting close channels since there may be settles or fails that need to be
1878
// reforwarded before they completely close.
1879
func (s *Switch) reforwardResponses() error {
210✔
1880
        openChannels, err := s.cfg.FetchAllChannels()
210✔
1881
        if err != nil {
210✔
1882
                return err
×
1883
        }
×
1884

1885
        for _, openChannel := range openChannels {
342✔
1886
                shortChanID := openChannel.ShortChanID()
132✔
1887

132✔
1888
                // Locally-initiated payments never need reforwarding.
132✔
1889
                if shortChanID == hop.Source {
135✔
1890
                        continue
3✔
1891
                }
1892

1893
                // If the channel is pending, it should have no forwarding
1894
                // packages, and nothing to reforward.
1895
                if openChannel.IsPending {
132✔
1896
                        continue
×
1897
                }
1898

1899
                // Channels in open or waiting-close may still have responses in
1900
                // their forwarding packages. We will continue to reattempt
1901
                // forwarding on startup until the channel is fully-closed.
1902
                //
1903
                // Load this channel's forwarding packages, and deliver them to
1904
                // the switch.
1905
                fwdPkgs, err := s.loadChannelFwdPkgs(shortChanID)
132✔
1906
                if err != nil {
132✔
1907
                        log.Errorf("unable to load forwarding "+
×
1908
                                "packages for %v: %v", shortChanID, err)
×
1909
                        return err
×
1910
                }
×
1911

1912
                s.reforwardSettleFails(fwdPkgs)
132✔
1913
        }
1914

1915
        return nil
210✔
1916
}
1917

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

132✔
1922
        var fwdPkgs []*channeldb.FwdPkg
132✔
1923
        if err := kvdb.View(s.cfg.DB, func(tx kvdb.RTx) error {
264✔
1924
                var err error
132✔
1925
                fwdPkgs, err = s.cfg.SwitchPackager.LoadChannelFwdPkgs(
132✔
1926
                        tx, source,
132✔
1927
                )
132✔
1928
                return err
132✔
1929
        }, func() {
264✔
1930
                fwdPkgs = nil
132✔
1931
        }); err != nil {
132✔
1932
                return nil, err
×
1933
        }
×
1934

1935
        return fwdPkgs, nil
132✔
1936
}
1937

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

1956
                        switch msg := update.UpdateMsg.(type) {
3✔
1957
                        // A settle for an HTLC we previously forwarded HTLC has
1958
                        // been received. So we'll forward the HTLC to the
1959
                        // switch which will handle propagating the settle to
1960
                        // the prior hop.
1961
                        case *lnwire.UpdateFulfillHTLC:
3✔
1962
                                destRef := fwdPkg.DestRef(uint16(i))
3✔
1963
                                settlePacket := &htlcPacket{
3✔
1964
                                        outgoingChanID: fwdPkg.Source,
3✔
1965
                                        outgoingHTLCID: msg.ID,
3✔
1966
                                        destRef:        &destRef,
3✔
1967
                                        htlc:           msg,
3✔
1968
                                }
3✔
1969

3✔
1970
                                // Add the packet to the batch to be forwarded, and
3✔
1971
                                // notify the overflow queue that a spare spot has been
3✔
1972
                                // freed up within the commitment state.
3✔
1973
                                switchPackets = append(switchPackets, settlePacket)
3✔
1974

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

×
1997
                                // Add the packet to the batch to be forwarded, and
×
1998
                                // notify the overflow queue that a spare spot has been
×
1999
                                // freed up within the commitment state.
×
2000
                                switchPackets = append(switchPackets, failPacket)
×
2001
                        }
2002
                }
2003

2004
                // Since this send isn't tied to a specific link, we pass a nil
2005
                // link quit channel, meaning the send will fail only if the
2006
                // switch receives a shutdown request.
2007
                if err := s.ForwardPackets(nil, switchPackets...); err != nil {
4✔
2008
                        log.Errorf("Unhandled error while reforwarding packets "+
×
2009
                                "settle/fail over htlcswitch: %v", err)
×
2010
                }
×
2011
        }
2012
}
2013

2014
// Stop gracefully stops all active helper goroutines, then waits until they've
2015
// exited.
2016
func (s *Switch) Stop() error {
442✔
2017
        if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
572✔
2018
                log.Warn("Htlc Switch already stopped")
130✔
2019
                return errors.New("htlc switch already shutdown")
130✔
2020
        }
130✔
2021

2022
        log.Info("HTLC Switch shutting down...")
312✔
2023
        defer log.Debug("HTLC Switch shutdown complete")
312✔
2024

312✔
2025
        close(s.quit)
312✔
2026

312✔
2027
        s.wg.Wait()
312✔
2028

312✔
2029
        // Wait until all active goroutines have finished exiting before
312✔
2030
        // stopping the mailboxes, otherwise the mailbox map could still be
312✔
2031
        // accessed and modified.
312✔
2032
        s.mailOrchestrator.Stop()
312✔
2033

312✔
2034
        return nil
312✔
2035
}
2036

2037
// CreateAndAddLink will create a link and then add it to the internal maps
2038
// when given a ChannelLinkConfig and LightningChannel.
2039
func (s *Switch) CreateAndAddLink(linkCfg ChannelLinkConfig,
2040
        lnChan *lnwallet.LightningChannel) error {
3✔
2041

3✔
2042
        link := NewChannelLink(linkCfg, lnChan)
3✔
2043
        return s.AddLink(link)
3✔
2044
}
3✔
2045

2046
// AddLink is used to initiate the handling of the add link command. The
2047
// request will be propagated and handled in the main goroutine.
2048
func (s *Switch) AddLink(link ChannelLink) error {
339✔
2049
        s.indexMtx.Lock()
339✔
2050
        defer s.indexMtx.Unlock()
339✔
2051

339✔
2052
        chanID := link.ChanID()
339✔
2053

339✔
2054
        // First, ensure that this link is not already active in the switch.
339✔
2055
        _, err := s.getLink(chanID)
339✔
2056
        if err == nil {
340✔
2057
                return fmt.Errorf("unable to add ChannelLink(%v), already "+
1✔
2058
                        "active", chanID)
1✔
2059
        }
1✔
2060

2061
        // Get and attach the mailbox for this link, which buffers packets in
2062
        // case there packets that we tried to deliver while this link was
2063
        // offline.
2064
        shortChanID := link.ShortChanID()
338✔
2065
        mailbox := s.mailOrchestrator.GetOrCreateMailBox(chanID, shortChanID)
338✔
2066
        link.AttachMailBox(mailbox)
338✔
2067

338✔
2068
        // Attach the Switch's failAliasUpdate function to the link.
338✔
2069
        link.attachFailAliasUpdate(s.failAliasUpdate)
338✔
2070

338✔
2071
        if err := link.Start(); err != nil {
338✔
2072
                log.Errorf("AddLink failed to start link with chanID=%v: %v",
×
2073
                        chanID, err)
×
2074
                s.removeLink(chanID)
×
2075
                return err
×
2076
        }
×
2077

2078
        if shortChanID == hop.Source {
342✔
2079
                log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
4✔
2080
                        chanID, shortChanID)
4✔
2081

4✔
2082
                s.pendingLinkIndex[chanID] = link
4✔
2083
        } else {
341✔
2084
                log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
337✔
2085
                        chanID, shortChanID)
337✔
2086

337✔
2087
                s.addLiveLink(link)
337✔
2088
                s.mailOrchestrator.BindLiveShortChanID(
337✔
2089
                        mailbox, chanID, shortChanID,
337✔
2090
                )
337✔
2091
        }
337✔
2092

2093
        return nil
338✔
2094
}
2095

2096
// addLiveLink adds a link to all associated forwarding index, this makes it a
2097
// candidate for forwarding HTLCs.
2098
func (s *Switch) addLiveLink(link ChannelLink) {
337✔
2099
        linkScid := link.ShortChanID()
337✔
2100

337✔
2101
        // We'll add the link to the linkIndex which lets us quickly
337✔
2102
        // look up a channel when we need to close or register it, and
337✔
2103
        // the forwarding index which'll be used when forwarding HTLC's
337✔
2104
        // in the multi-hop setting.
337✔
2105
        s.linkIndex[link.ChanID()] = link
337✔
2106
        s.forwardingIndex[linkScid] = link
337✔
2107

337✔
2108
        // Next we'll add the link to the interface index so we can
337✔
2109
        // quickly look up all the channels for a particular node.
337✔
2110
        peerPub := link.PeerPubKey()
337✔
2111
        if _, ok := s.interfaceIndex[peerPub]; !ok {
669✔
2112
                s.interfaceIndex[peerPub] = make(map[lnwire.ChannelID]ChannelLink)
332✔
2113
        }
332✔
2114
        s.interfaceIndex[peerPub][link.ChanID()] = link
337✔
2115

337✔
2116
        s.updateLinkAliases(link)
337✔
2117
}
2118

2119
// UpdateLinkAliases is the externally exposed wrapper for updating link
2120
// aliases. It acquires the indexMtx and calls the internal method.
2121
func (s *Switch) UpdateLinkAliases(link ChannelLink) {
3✔
2122
        s.indexMtx.Lock()
3✔
2123
        defer s.indexMtx.Unlock()
3✔
2124

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

2128
// updateLinkAliases updates the aliases for a given link. This will cause the
2129
// htlcswitch to consult the alias manager on the up to date values of its
2130
// alias maps.
2131
//
2132
// NOTE: this MUST be called with the indexMtx held.
2133
func (s *Switch) updateLinkAliases(link ChannelLink) {
337✔
2134
        linkScid := link.ShortChanID()
337✔
2135

337✔
2136
        aliases := link.getAliases()
337✔
2137
        if link.isZeroConf() {
359✔
2138
                if link.zeroConfConfirmed() {
40✔
2139
                        // Since the zero-conf channel has confirmed, we can
18✔
2140
                        // populate the aliasToReal mapping.
18✔
2141
                        confirmedScid := link.confirmedScid()
18✔
2142

18✔
2143
                        for _, alias := range aliases {
43✔
2144
                                s.aliasToReal[alias] = confirmedScid
25✔
2145
                        }
25✔
2146

2147
                        // Add the confirmed SCID as a key in the baseIndex.
2148
                        s.baseIndex[confirmedScid] = linkScid
18✔
2149
                }
2150

2151
                // Now we populate the baseIndex which will be used to fetch
2152
                // the link given any of the channel's alias SCIDs or the real
2153
                // SCID. The link's SCID is an alias, so we don't need to
2154
                // special-case it like the option-scid-alias feature-bit case
2155
                // further down.
2156
                for _, alias := range aliases {
52✔
2157
                        s.baseIndex[alias] = linkScid
30✔
2158
                }
30✔
2159
        } else if link.negotiatedAliasFeature() {
337✔
2160
                // First, we flush any alias mappings for this link's scid
19✔
2161
                // before we populate the map again, in order to get rid of old
19✔
2162
                // values that no longer exist.
19✔
2163
                for alias, real := range s.aliasToReal {
24✔
2164
                        if real == linkScid {
8✔
2165
                                delete(s.aliasToReal, alias)
3✔
2166
                        }
3✔
2167
                }
2168

2169
                for alias, real := range s.baseIndex {
25✔
2170
                        if real == linkScid {
9✔
2171
                                delete(s.baseIndex, alias)
3✔
2172
                        }
3✔
2173
                }
2174

2175
                // The link's SCID is the confirmed SCID for non-zero-conf
2176
                // option-scid-alias feature bit channels.
2177
                for _, alias := range aliases {
45✔
2178
                        s.aliasToReal[alias] = linkScid
26✔
2179
                        s.baseIndex[alias] = linkScid
26✔
2180
                }
26✔
2181

2182
                // Since the link's SCID is confirmed, it was not included in
2183
                // the baseIndex above as a key. Add it now.
2184
                s.baseIndex[linkScid] = linkScid
19✔
2185
        }
2186
}
2187

2188
// GetLink is used to initiate the handling of the get link command. The
2189
// request will be propagated/handled to/in the main goroutine.
2190
func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelUpdateHandler,
2191
        error) {
3,158✔
2192

3,158✔
2193
        s.indexMtx.RLock()
3,158✔
2194
        defer s.indexMtx.RUnlock()
3,158✔
2195

3,158✔
2196
        return s.getLink(chanID)
3,158✔
2197
}
3,158✔
2198

2199
// getLink returns the link stored in either the pending index or the live
2200
// lindex.
2201
func (s *Switch) getLink(chanID lnwire.ChannelID) (ChannelLink, error) {
3,823✔
2202
        link, ok := s.linkIndex[chanID]
3,823✔
2203
        if !ok {
4,163✔
2204
                link, ok = s.pendingLinkIndex[chanID]
340✔
2205
                if !ok {
679✔
2206
                        return nil, ErrChannelLinkNotFound
339✔
2207
                }
339✔
2208
        }
2209

2210
        return link, nil
3,487✔
2211
}
2212

2213
// GetLinkByShortID attempts to return the link which possesses the target short
2214
// channel ID.
2215
func (s *Switch) GetLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink,
2216
        error) {
3✔
2217

3✔
2218
        s.indexMtx.RLock()
3✔
2219
        defer s.indexMtx.RUnlock()
3✔
2220

3✔
2221
        link, err := s.getLinkByShortID(chanID)
3✔
2222
        if err != nil {
6✔
2223
                // If we failed to find the link under the passed-in SCID, we
3✔
2224
                // consult the Switch's baseIndex map to see if the confirmed
3✔
2225
                // SCID was used for a zero-conf channel.
3✔
2226
                aliasID, ok := s.baseIndex[chanID]
3✔
2227
                if !ok {
6✔
2228
                        return nil, err
3✔
2229
                }
3✔
2230

2231
                // An alias was found, use it to lookup if a link exists.
2232
                return s.getLinkByShortID(aliasID)
3✔
2233
        }
2234

2235
        return link, nil
3✔
2236
}
2237

2238
// getLinkByShortID attempts to return the link which possesses the target
2239
// short channel ID.
2240
//
2241
// NOTE: This MUST be called with the indexMtx held.
2242
func (s *Switch) getLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink, error) {
475✔
2243
        link, ok := s.forwardingIndex[chanID]
475✔
2244
        if !ok {
479✔
2245
                log.Debugf("Link not found in forwarding index using "+
4✔
2246
                        "chanID=%v", chanID)
4✔
2247

4✔
2248
                return nil, ErrChannelLinkNotFound
4✔
2249
        }
4✔
2250

2251
        return link, nil
474✔
2252
}
2253

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

82✔
2275
        log.Debugf("Querying outgoing link using chanID=%v, aliasID=%v", chanID,
82✔
2276
                aliasID)
82✔
2277

82✔
2278
        // Set the originalOutgoingChanID so the proper channel_update can be
82✔
2279
        // sent back if the option-scid-alias feature bit was negotiated.
82✔
2280
        pkt.originalOutgoingChanID = chanID
82✔
2281

82✔
2282
        if aliasID {
100✔
2283
                // Since outgoingChanID is an alias, we'll fetch the link via
18✔
2284
                // baseIndex.
18✔
2285
                baseScid, ok := s.baseIndex[chanID]
18✔
2286
                if !ok {
18✔
2287
                        // No mapping exists, bail.
×
2288
                        return nil, ErrChannelLinkNotFound
×
2289
                }
×
2290

2291
                // A mapping exists, so use baseScid to find the link in the
2292
                // forwardingIndex.
2293
                link, ok := s.forwardingIndex[baseScid]
18✔
2294
                if !ok {
18✔
2295
                        log.Debugf("Forwarding index not found using "+
×
2296
                                "baseScid=%v", baseScid)
×
2297

×
2298
                        // Link not found, bail.
×
2299
                        return nil, ErrChannelLinkNotFound
×
2300
                }
×
2301

2302
                // Change the packet's outgoingChanID field so that errors are
2303
                // properly attributed.
2304
                pkt.outgoingChanID = baseScid
18✔
2305

18✔
2306
                // Return the link without checking if it's private or not.
18✔
2307
                return link, nil
18✔
2308
        }
2309

2310
        // The outgoingChanID is a confirmed SCID. Attempt to fetch the base
2311
        // SCID from baseIndex.
2312
        baseScid, ok := s.baseIndex[chanID]
67✔
2313
        if !ok {
127✔
2314
                // outgoingChanID is not a key in base index meaning this
60✔
2315
                // channel did not have the option-scid-alias feature bit
60✔
2316
                // negotiated. We'll fetch the link and return it.
60✔
2317
                link, ok := s.forwardingIndex[chanID]
60✔
2318
                if !ok {
65✔
2319
                        log.Debugf("Forwarding index not found using "+
5✔
2320
                                "chanID=%v", chanID)
5✔
2321

5✔
2322
                        // The link wasn't found, bail out.
5✔
2323
                        return nil, ErrChannelLinkNotFound
5✔
2324
                }
5✔
2325

2326
                return link, nil
58✔
2327
        }
2328

2329
        // Fetch the link whose internal SCID is baseScid.
2330
        link, ok := s.forwardingIndex[baseScid]
10✔
2331
        if !ok {
10✔
2332
                log.Debugf("Forwarding index not found using baseScid=%v",
×
2333
                        baseScid)
×
2334

×
2335
                // Link wasn't found, bail out.
×
2336
                return nil, ErrChannelLinkNotFound
×
2337
        }
×
2338

2339
        // If the link is unadvertised, we fail since the real SCID was used to
2340
        // forward over it and this is a channel where the option-scid-alias
2341
        // feature bit was negotiated.
2342
        if link.IsUnadvertised() {
12✔
2343
                log.Debugf("Link is unadvertised, chanID=%v, baseScid=%v",
2✔
2344
                        chanID, baseScid)
2✔
2345

2✔
2346
                return nil, ErrChannelLinkNotFound
2✔
2347
        }
2✔
2348

2349
        // The link is public so the confirmed SCID can be used to forward over
2350
        // it. We'll also replace pkt's outgoingChanID field so errors can
2351
        // properly be attributed in the calling function.
2352
        pkt.outgoingChanID = baseScid
8✔
2353
        return link, nil
8✔
2354
}
2355

2356
// HasActiveLink returns true if the given channel ID has a link in the link
2357
// index AND the link is eligible to forward.
2358
func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
5✔
2359
        s.indexMtx.RLock()
5✔
2360
        defer s.indexMtx.RUnlock()
5✔
2361

5✔
2362
        if link, ok := s.linkIndex[chanID]; ok {
10✔
2363
                return link.EligibleToForward()
5✔
2364
        }
5✔
2365

2366
        return false
3✔
2367
}
2368

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

2384
        // Check if the link is already stopping and grab the stop chan if it
2385
        // is.
2386
        stopChan, ok := s.linkStopIndex[chanID]
21✔
2387
        if !ok {
42✔
2388
                // If the link is non-nil, it is not currently stopping, so
21✔
2389
                // we'll add a stop chan to the linkStopIndex.
21✔
2390
                stopChan = make(chan struct{})
21✔
2391
                s.linkStopIndex[chanID] = stopChan
21✔
2392
        }
21✔
2393
        s.indexMtx.Unlock()
21✔
2394

21✔
2395
        if ok {
21✔
2396
                // If the stop chan exists, we will wait for it to be closed.
×
2397
                // Once it is closed, we will exit.
×
2398
                select {
×
2399
                case <-stopChan:
×
2400
                        return
×
2401
                case <-s.quit:
×
2402
                        return
×
2403
                }
2404
        }
2405

2406
        // Stop the link before removing it from the maps.
2407
        link.Stop()
21✔
2408

21✔
2409
        s.indexMtx.Lock()
21✔
2410
        _ = s.removeLink(chanID)
21✔
2411

21✔
2412
        // Close stopChan and remove this link from the linkStopIndex.
21✔
2413
        // Deleting from the index and removing from the link must be done
21✔
2414
        // in the same block while the mutex is held.
21✔
2415
        close(stopChan)
21✔
2416
        delete(s.linkStopIndex, chanID)
21✔
2417
        s.indexMtx.Unlock()
21✔
2418
}
2419

2420
// removeLink is used to remove and stop the channel link.
2421
//
2422
// NOTE: This MUST be called with the indexMtx held.
2423
func (s *Switch) removeLink(chanID lnwire.ChannelID) ChannelLink {
314✔
2424
        log.Infof("Removing channel link with ChannelID(%v)", chanID)
314✔
2425

314✔
2426
        link, err := s.getLink(chanID)
314✔
2427
        if err != nil {
314✔
2428
                return nil
×
2429
        }
×
2430

2431
        // Remove the channel from live link indexes.
2432
        delete(s.pendingLinkIndex, link.ChanID())
314✔
2433
        delete(s.linkIndex, link.ChanID())
314✔
2434
        delete(s.forwardingIndex, link.ShortChanID())
314✔
2435

314✔
2436
        // If the link has been added to the peer index, then we'll move to
314✔
2437
        // delete the entry within the index.
314✔
2438
        peerPub := link.PeerPubKey()
314✔
2439
        if peerIndex, ok := s.interfaceIndex[peerPub]; ok {
627✔
2440
                delete(peerIndex, link.ChanID())
313✔
2441

313✔
2442
                // If after deletion, there are no longer any links, then we'll
313✔
2443
                // remove the interface map all together.
313✔
2444
                if len(peerIndex) == 0 {
621✔
2445
                        delete(s.interfaceIndex, peerPub)
308✔
2446
                }
308✔
2447
        }
2448

2449
        return link
314✔
2450
}
2451

2452
// UpdateShortChanID locates the link with the passed-in chanID and updates the
2453
// underlying channel state. This is only used in zero-conf channels to allow
2454
// the confirmed SCID to be updated.
2455
func (s *Switch) UpdateShortChanID(chanID lnwire.ChannelID) error {
4✔
2456
        s.indexMtx.Lock()
4✔
2457
        defer s.indexMtx.Unlock()
4✔
2458

4✔
2459
        // Locate the target link in the link index. If no such link exists,
4✔
2460
        // then we will ignore the request.
4✔
2461
        link, ok := s.linkIndex[chanID]
4✔
2462
        if !ok {
4✔
2463
                return fmt.Errorf("link %v not found", chanID)
×
2464
        }
×
2465

2466
        // Try to update the link's underlying channel state, returning early
2467
        // if this update failed.
2468
        _, err := link.UpdateShortChanID()
4✔
2469
        if err != nil {
4✔
2470
                return err
×
2471
        }
×
2472

2473
        // Since the zero-conf channel is confirmed, we should populate the
2474
        // aliasToReal map and update the baseIndex.
2475
        aliases := link.getAliases()
4✔
2476

4✔
2477
        confirmedScid := link.confirmedScid()
4✔
2478

4✔
2479
        for _, alias := range aliases {
9✔
2480
                s.aliasToReal[alias] = confirmedScid
5✔
2481
        }
5✔
2482

2483
        s.baseIndex[confirmedScid] = link.ShortChanID()
4✔
2484

4✔
2485
        return nil
4✔
2486
}
2487

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

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

3✔
2496
        var handlers []ChannelUpdateHandler
3✔
2497

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

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

2509
        return handlers, nil
3✔
2510
}
2511

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

2522
        channelLinks := make([]ChannelLink, 0, len(links))
78✔
2523
        for _, link := range links {
160✔
2524
                channelLinks = append(channelLinks, link)
82✔
2525
        }
82✔
2526

2527
        return channelLinks, nil
78✔
2528
}
2529

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

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

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

17✔
2546
        return s.circuits.CommitCircuits(circuits...)
17✔
2547
}
17✔
2548

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

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

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

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

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

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

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

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

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

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

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

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

398✔
2626
                // Optionally include the HTLC amount only for outgoing
398✔
2627
                // HTLCs.
398✔
2628
                if !incoming {
757✔
2629
                        localSum += amount
359✔
2630
                }
359✔
2631

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

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

396✔
2646
                // Optionally include the HTLC amount only for outgoing
396✔
2647
                // HTLCs.
396✔
2648
                if !incoming {
753✔
2649
                        remoteSum += amount
357✔
2650
                }
357✔
2651

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

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

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

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

2685
        return lnwire.NewTemporaryChannelFailure(update)
10✔
2686
}
2687

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

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

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

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

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

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

2734
                        return update
×
2735
                }
2736

2737
                s.indexMtx.RUnlock()
14✔
2738

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

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

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

2760
                return update
14✔
2761
        }
2762

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

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

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

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

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

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

2816
        return update
5✔
2817
}
2818

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

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

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

2839
        linkScid := link.ShortChanID()
×
2840

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

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

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

2861
        return nil
×
2862
}
2863

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

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

4✔
2876
                return s.failAddPacket(packet, failure)
4✔
2877
        }
4✔
2878

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

2895
        s.indexMtx.RLock()
82✔
2896
        targetLink, err := s.getLinkByMapping(packet)
82✔
2897
        if err != nil {
89✔
2898
                s.indexMtx.RUnlock()
7✔
2899

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

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

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

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

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

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

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

2953
                linkErrs[link.ShortChanID()] = failure
23✔
2954
        }
2955

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

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

19✔
2982
                return s.failAddPacket(packet, linkErr)
19✔
2983
        }
2984

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

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

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

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

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

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

1✔
3031
                return s.failAddPacket(packet, linkErr)
1✔
3032
        }
1✔
3033

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

61✔
3038
        return destination.handleSwitchPacket(packet)
61✔
3039
}
3040

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

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

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

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

3070
        localHTLC := packet.incomingChanID == hop.Source
212✔
3071

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

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

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

32✔
3099
                s.fwdEventMtx.Lock()
32✔
3100
                s.pendingFwdingEvents = append(
32✔
3101
                        s.pendingFwdingEvents,
32✔
3102
                        channeldb.ForwardingEvent{
32✔
3103
                                Timestamp:      time.Now(),
32✔
3104
                                IncomingChanID: circuit.Incoming.ChanID,
32✔
3105
                                OutgoingChanID: circuit.Outgoing.ChanID,
32✔
3106
                                AmtIn:          circuit.IncomingAmount,
32✔
3107
                                AmtOut:         circuit.OutgoingAmount,
32✔
3108
                                IncomingHtlcID: fn.Some(
32✔
3109
                                        circuit.Incoming.HtlcID,
32✔
3110
                                ),
32✔
3111
                                OutgoingHtlcID: fn.Some(
32✔
3112
                                        circuit.Outgoing.HtlcID,
32✔
3113
                                ),
32✔
3114
                        },
32✔
3115
                )
32✔
3116
                s.fwdEventMtx.Unlock()
32✔
3117
        }
32✔
3118

3119
        // Deliver this packet.
3120
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
32✔
3121
}
3122

3123
// handlePacketFail handles forwarding a fail packet.
3124
func (s *Switch) handlePacketFail(packet *htlcPacket,
3125
        htlc *lnwire.UpdateFailHTLC) error {
136✔
3126

136✔
3127
        // If the source of this packet has not been set, use the circuit map
136✔
3128
        // to lookup the origin.
136✔
3129
        circuit, err := s.closeCircuit(packet)
136✔
3130
        if err != nil {
136✔
3131
                return err
×
3132
        }
×
3133

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

123✔
3146
                // If this is a locally initiated HTLC, there's no need to
123✔
3147
                // forward it so we exit.
123✔
3148
                return nil
123✔
3149
        }
123✔
3150

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

3163
        // HTLC resolutions and messages restored from disk don't have the
3164
        // obfuscator set from the original htlc add packet - set it here for
3165
        // use in blinded errors.
3166
        packet.obfuscator = circuit.ErrorEncrypter
10✔
3167

10✔
3168
        switch {
10✔
3169
        // No message to encrypt, locally sourced payment.
3170
        case circuit.ErrorEncrypter == nil:
×
3171
                // TODO(yy) further check this case as we shouldn't end up here
3172
                // as `isLocal` is already false.
3173

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

3188
                htlc.Reason = reason
3✔
3189
                htlc.ExtraData, err = lnwire.AttrDataToExtraData(attrData)
3✔
3190
                if err != nil {
3✔
NEW
3191
                        return err
×
NEW
3192
                }
×
3193

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

5✔
3204
                reason, attrData, err :=
5✔
3205
                        circuit.ErrorEncrypter.EncryptMalformedError(
5✔
3206
                                htlc.Reason,
5✔
3207
                        )
5✔
3208
                if err != nil {
5✔
NEW
3209
                        return err
×
NEW
3210
                }
×
3211

3212
                htlc.Reason = reason
5✔
3213
                htlc.ExtraData, err = lnwire.AttrDataToExtraData(attrData)
5✔
3214
                if err != nil {
5✔
NEW
3215
                        return err
×
NEW
3216
                }
×
3217

3218
        default:
8✔
3219
                attrData, err := lnwire.ExtraDataToAttrData(htlc.ExtraData)
8✔
3220
                if err != nil {
8✔
NEW
3221
                        return err
×
NEW
3222
                }
×
3223

3224
                // Otherwise, it's a forwarded error, so we'll perform a
3225
                // wrapper encryption as normal.
3226
                reason, attrData, err :=
8✔
3227
                        circuit.ErrorEncrypter.IntermediateEncrypt(
8✔
3228
                                htlc.Reason, attrData,
8✔
3229
                        )
8✔
3230
                if err != nil {
8✔
NEW
3231
                        return err
×
NEW
3232
                }
×
3233

3234
                htlc.Reason = reason
8✔
3235
                htlc.ExtraData, err = lnwire.AttrDataToExtraData(attrData)
8✔
3236
                if err != nil {
8✔
NEW
3237
                        return err
×
NEW
3238
                }
×
3239
        }
3240

3241
        // Deliver this packet.
3242
        return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
10✔
3243
}
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