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

lightningnetwork / lnd / 11170835610

03 Oct 2024 10:41PM UTC coverage: 49.188% (-9.6%) from 58.738%
11170835610

push

github

web-flow
Merge pull request #9154 from ziggie1984/master

multi: bump btcd version.

3 of 6 new or added lines in 6 files covered. (50.0%)

26110 existing lines in 428 files now uncovered.

97359 of 197934 relevant lines covered (49.19%)

1.04 hits per line

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

76.62
/invoices/invoiceregistry.go
1
package invoices
2

3
import (
4
        "context"
5
        "errors"
6
        "fmt"
7
        "sync"
8
        "sync/atomic"
9
        "time"
10

11
        "github.com/lightningnetwork/lnd/clock"
12
        "github.com/lightningnetwork/lnd/lntypes"
13
        "github.com/lightningnetwork/lnd/lnwire"
14
        "github.com/lightningnetwork/lnd/queue"
15
        "github.com/lightningnetwork/lnd/record"
16
)
17

18
var (
19
        // ErrInvoiceExpiryTooSoon is returned when an invoice is attempted to
20
        // be accepted or settled with not enough blocks remaining.
21
        ErrInvoiceExpiryTooSoon = errors.New("invoice expiry too soon")
22

23
        // ErrInvoiceAmountTooLow is returned  when an invoice is attempted to
24
        // be accepted or settled with an amount that is too low.
25
        ErrInvoiceAmountTooLow = errors.New(
26
                "paid amount less than invoice amount",
27
        )
28

29
        // ErrShuttingDown is returned when an operation failed because the
30
        // invoice registry is shutting down.
31
        ErrShuttingDown = errors.New("invoice registry shutting down")
32
)
33

34
const (
35
        // DefaultHtlcHoldDuration defines the default for how long mpp htlcs
36
        // are held while waiting for the other set members to arrive.
37
        DefaultHtlcHoldDuration = 120 * time.Second
38
)
39

40
// RegistryConfig contains the configuration parameters for invoice registry.
41
type RegistryConfig struct {
42
        // FinalCltvRejectDelta defines the number of blocks before the expiry
43
        // of the htlc where we no longer settle it as an exit hop and instead
44
        // cancel it back. Normally this value should be lower than the cltv
45
        // expiry of any invoice we create and the code effectuating this should
46
        // not be hit.
47
        FinalCltvRejectDelta int32
48

49
        // HtlcHoldDuration defines for how long mpp htlcs are held while
50
        // waiting for the other set members to arrive.
51
        HtlcHoldDuration time.Duration
52

53
        // Clock holds the clock implementation that is used to provide
54
        // Now() and TickAfter() and is useful to stub out the clock functions
55
        // during testing.
56
        Clock clock.Clock
57

58
        // AcceptKeySend indicates whether we want to accept spontaneous key
59
        // send payments.
60
        AcceptKeySend bool
61

62
        // AcceptAMP indicates whether we want to accept spontaneous AMP
63
        // payments.
64
        AcceptAMP bool
65

66
        // GcCanceledInvoicesOnStartup if set, we'll attempt to garbage collect
67
        // all canceled invoices upon start.
68
        GcCanceledInvoicesOnStartup bool
69

70
        // GcCanceledInvoicesOnTheFly if set, we'll garbage collect all newly
71
        // canceled invoices on the fly.
72
        GcCanceledInvoicesOnTheFly bool
73

74
        // KeysendHoldTime indicates for how long we want to accept and hold
75
        // spontaneous keysend payments.
76
        KeysendHoldTime time.Duration
77

78
        // HtlcInterceptor is an interface that allows the invoice registry to
79
        // let clients intercept invoices before they are settled.
80
        HtlcInterceptor HtlcInterceptor
81
}
82

83
// htlcReleaseEvent describes an htlc auto-release event. It is used to release
84
// mpp htlcs for which the complete set didn't arrive in time.
85
type htlcReleaseEvent struct {
86
        // invoiceRef identifiers the invoice this htlc belongs to.
87
        invoiceRef InvoiceRef
88

89
        // key is the circuit key of the htlc to release.
90
        key CircuitKey
91

92
        // releaseTime is the time at which to release the htlc.
93
        releaseTime time.Time
94
}
95

96
// Less is used to order PriorityQueueItem's by their release time such that
97
// items with the older release time are at the top of the queue.
98
//
99
// NOTE: Part of the queue.PriorityQueueItem interface.
100
func (r *htlcReleaseEvent) Less(other queue.PriorityQueueItem) bool {
2✔
101
        return r.releaseTime.Before(other.(*htlcReleaseEvent).releaseTime)
2✔
102
}
2✔
103

104
// InvoiceRegistry is a central registry of all the outstanding invoices
105
// created by the daemon. The registry is a thin wrapper around a map in order
106
// to ensure that all updates/reads are thread safe.
107
type InvoiceRegistry struct {
108
        started atomic.Bool
109
        stopped atomic.Bool
110

111
        sync.RWMutex
112

113
        nextClientID uint32 // must be used atomically
114

115
        idb InvoiceDB
116

117
        // cfg contains the registry's configuration parameters.
118
        cfg *RegistryConfig
119

120
        // notificationClientMux locks notificationClients and
121
        // singleNotificationClients. Using a separate mutex for these maps is
122
        // necessary to avoid deadlocks in the registry when processing invoice
123
        // events.
124
        notificationClientMux sync.RWMutex
125

126
        notificationClients map[uint32]*InvoiceSubscription
127

128
        // TODO(yy): use map[lntypes.Hash]*SingleInvoiceSubscription for better
129
        // performance.
130
        singleNotificationClients map[uint32]*SingleInvoiceSubscription
131

132
        // invoiceEvents is a single channel over which invoice updates are
133
        // carried.
134
        invoiceEvents chan *invoiceEvent
135

136
        // hodlSubscriptionsMux locks the hodlSubscriptions and
137
        // hodlReverseSubscriptions. Using a separate mutex for these maps is
138
        // necessary to avoid deadlocks in the registry when processing invoice
139
        // events.
140
        hodlSubscriptionsMux sync.RWMutex
141

142
        // hodlSubscriptions is a map from a circuit key to a list of
143
        // subscribers. It is used for efficient notification of links.
144
        hodlSubscriptions map[CircuitKey]map[chan<- interface{}]struct{}
145

146
        // reverseSubscriptions tracks circuit keys subscribed to per
147
        // subscriber. This is used to unsubscribe from all hashes efficiently.
148
        hodlReverseSubscriptions map[chan<- interface{}]map[CircuitKey]struct{}
149

150
        // htlcAutoReleaseChan contains the new htlcs that need to be
151
        // auto-released.
152
        htlcAutoReleaseChan chan *htlcReleaseEvent
153

154
        expiryWatcher *InvoiceExpiryWatcher
155

156
        wg   sync.WaitGroup
157
        quit chan struct{}
158
}
159

160
// NewRegistry creates a new invoice registry. The invoice registry
161
// wraps the persistent on-disk invoice storage with an additional in-memory
162
// layer. The in-memory layer is in place such that debug invoices can be added
163
// which are volatile yet available system wide within the daemon.
164
func NewRegistry(idb InvoiceDB, expiryWatcher *InvoiceExpiryWatcher,
165
        cfg *RegistryConfig) *InvoiceRegistry {
2✔
166

2✔
167
        notificationClients := make(map[uint32]*InvoiceSubscription)
2✔
168
        singleNotificationClients := make(map[uint32]*SingleInvoiceSubscription)
2✔
169
        return &InvoiceRegistry{
2✔
170
                idb:                       idb,
2✔
171
                notificationClients:       notificationClients,
2✔
172
                singleNotificationClients: singleNotificationClients,
2✔
173
                invoiceEvents:             make(chan *invoiceEvent, 100),
2✔
174
                hodlSubscriptions: make(
2✔
175
                        map[CircuitKey]map[chan<- interface{}]struct{},
2✔
176
                ),
2✔
177
                hodlReverseSubscriptions: make(
2✔
178
                        map[chan<- interface{}]map[CircuitKey]struct{},
2✔
179
                ),
2✔
180
                cfg:                 cfg,
2✔
181
                htlcAutoReleaseChan: make(chan *htlcReleaseEvent),
2✔
182
                expiryWatcher:       expiryWatcher,
2✔
183
                quit:                make(chan struct{}),
2✔
184
        }
2✔
185
}
2✔
186

187
// scanInvoicesOnStart will scan all invoices on start and add active invoices
188
// to the invoice expiry watcher while also attempting to delete all canceled
189
// invoices.
190
func (i *InvoiceRegistry) scanInvoicesOnStart(ctx context.Context) error {
2✔
191
        pendingInvoices, err := i.idb.FetchPendingInvoices(ctx)
2✔
192
        if err != nil {
2✔
193
                return err
×
194
        }
×
195

196
        var pending []invoiceExpiry
2✔
197
        for paymentHash, invoice := range pendingInvoices {
4✔
198
                invoice := invoice
2✔
199
                expiryRef := makeInvoiceExpiry(paymentHash, &invoice)
2✔
200
                if expiryRef != nil {
4✔
201
                        pending = append(pending, expiryRef)
2✔
202
                }
2✔
203
        }
204

205
        log.Debugf("Adding %d pending invoices to the expiry watcher",
2✔
206
                len(pending))
2✔
207
        i.expiryWatcher.AddInvoices(pending...)
2✔
208

2✔
209
        if i.cfg.GcCanceledInvoicesOnStartup {
2✔
UNCOV
210
                log.Infof("Deleting canceled invoices")
×
UNCOV
211
                err = i.idb.DeleteCanceledInvoices(ctx)
×
UNCOV
212
                if err != nil {
×
213
                        log.Warnf("Deleting canceled invoices failed: %v", err)
×
214
                        return err
×
215
                }
×
216
        }
217

218
        return nil
2✔
219
}
220

221
// Start starts the registry and all goroutines it needs to carry out its task.
222
func (i *InvoiceRegistry) Start() error {
2✔
223
        var err error
2✔
224

2✔
225
        log.Info("InvoiceRegistry starting...")
2✔
226

2✔
227
        if i.started.Swap(true) {
2✔
228
                return fmt.Errorf("InvoiceRegistry started more than once")
×
229
        }
×
230
        // Start InvoiceExpiryWatcher and prepopulate it with existing
231
        // active invoices.
232
        err = i.expiryWatcher.Start(
2✔
233
                func(hash lntypes.Hash, force bool) error {
4✔
234
                        return i.cancelInvoiceImpl(
2✔
235
                                context.Background(), hash, force,
2✔
236
                        )
2✔
237
                })
2✔
238
        if err != nil {
2✔
239
                return err
×
240
        }
×
241

242
        i.wg.Add(1)
2✔
243
        go i.invoiceEventLoop()
2✔
244

2✔
245
        // Now scan all pending and removable invoices to the expiry
2✔
246
        // watcher or delete them.
2✔
247
        err = i.scanInvoicesOnStart(context.Background())
2✔
248
        if err != nil {
2✔
249
                _ = i.Stop()
×
250
        }
×
251

252
        log.Debug("InvoiceRegistry started")
2✔
253

2✔
254
        return err
2✔
255
}
256

257
// Stop signals the registry for a graceful shutdown.
258
func (i *InvoiceRegistry) Stop() error {
2✔
259
        log.Info("InvoiceRegistry shutting down...")
2✔
260

2✔
261
        if i.stopped.Swap(true) {
2✔
262
                return fmt.Errorf("InvoiceRegistry stopped more than once")
×
263
        }
×
264

265
        log.Info("InvoiceRegistry shutting down...")
2✔
266
        defer log.Debug("InvoiceRegistry shutdown complete")
2✔
267

2✔
268
        var err error
2✔
269
        if i.expiryWatcher == nil {
2✔
270
                err = fmt.Errorf("InvoiceRegistry expiryWatcher is not " +
×
271
                        "initialized")
×
272
        } else {
2✔
273
                i.expiryWatcher.Stop()
2✔
274
        }
2✔
275

276
        close(i.quit)
2✔
277

2✔
278
        i.wg.Wait()
2✔
279

2✔
280
        log.Debug("InvoiceRegistry shutdown complete")
2✔
281

2✔
282
        return err
2✔
283
}
284

285
// invoiceEvent represents a new event that has modified on invoice on disk.
286
// Only two event types are currently supported: newly created invoices, and
287
// instance where invoices are settled.
288
type invoiceEvent struct {
289
        hash    lntypes.Hash
290
        invoice *Invoice
291
        setID   *[32]byte
292
}
293

294
// tickAt returns a channel that ticks at the specified time. If the time has
295
// already passed, it will tick immediately.
296
func (i *InvoiceRegistry) tickAt(t time.Time) <-chan time.Time {
2✔
297
        now := i.cfg.Clock.Now()
2✔
298
        return i.cfg.Clock.TickAfter(t.Sub(now))
2✔
299
}
2✔
300

301
// invoiceEventLoop is the dedicated goroutine responsible for accepting
302
// new notification subscriptions, cancelling old subscriptions, and
303
// dispatching new invoice events.
304
func (i *InvoiceRegistry) invoiceEventLoop() {
2✔
305
        defer i.wg.Done()
2✔
306

2✔
307
        // Set up a heap for htlc auto-releases.
2✔
308
        autoReleaseHeap := &queue.PriorityQueue{}
2✔
309

2✔
310
        for {
4✔
311
                // If there is something to release, set up a release tick
2✔
312
                // channel.
2✔
313
                var nextReleaseTick <-chan time.Time
2✔
314
                if autoReleaseHeap.Len() > 0 {
4✔
315
                        head := autoReleaseHeap.Top().(*htlcReleaseEvent)
2✔
316
                        nextReleaseTick = i.tickAt(head.releaseTime)
2✔
317
                }
2✔
318

319
                select {
2✔
320
                // A sub-systems has just modified the invoice state, so we'll
321
                // dispatch notifications to all registered clients.
322
                case event := <-i.invoiceEvents:
2✔
323
                        // For backwards compatibility, do not notify all
2✔
324
                        // invoice subscribers of cancel and accept events.
2✔
325
                        state := event.invoice.State
2✔
326
                        if state != ContractCanceled &&
2✔
327
                                state != ContractAccepted {
4✔
328

2✔
329
                                i.dispatchToClients(event)
2✔
330
                        }
2✔
331
                        i.dispatchToSingleClients(event)
2✔
332

333
                // A new htlc came in for auto-release.
334
                case event := <-i.htlcAutoReleaseChan:
2✔
335
                        log.Debugf("Scheduling auto-release for htlc: "+
2✔
336
                                "ref=%v, key=%v at %v",
2✔
337
                                event.invoiceRef, event.key, event.releaseTime)
2✔
338

2✔
339
                        // We use an independent timer for every htlc rather
2✔
340
                        // than a set timer that is reset with every htlc coming
2✔
341
                        // in. Otherwise the sender could keep resetting the
2✔
342
                        // timer until the broadcast window is entered and our
2✔
343
                        // channel is force closed.
2✔
344
                        autoReleaseHeap.Push(event)
2✔
345

346
                // The htlc at the top of the heap needs to be auto-released.
347
                case <-nextReleaseTick:
2✔
348
                        event := autoReleaseHeap.Pop().(*htlcReleaseEvent)
2✔
349
                        err := i.cancelSingleHtlc(
2✔
350
                                event.invoiceRef, event.key, ResultMppTimeout,
2✔
351
                        )
2✔
352
                        if err != nil {
2✔
353
                                log.Errorf("HTLC timer: %v", err)
×
354
                        }
×
355

356
                case <-i.quit:
2✔
357
                        return
2✔
358
                }
359
        }
360
}
361

362
// dispatchToSingleClients passes the supplied event to all notification
363
// clients that subscribed to all the invoice this event applies to.
364
func (i *InvoiceRegistry) dispatchToSingleClients(event *invoiceEvent) {
2✔
365
        // Dispatch to single invoice subscribers.
2✔
366
        clients := i.copySingleClients()
2✔
367
        for _, client := range clients {
4✔
368
                payHash := client.invoiceRef.PayHash()
2✔
369

2✔
370
                if payHash == nil || *payHash != event.hash {
4✔
371
                        continue
2✔
372
                }
373

374
                select {
2✔
375
                case <-client.backlogDelivered:
2✔
376
                        // We won't deliver any events until the backlog has
377
                        // went through first.
378
                case <-i.quit:
×
379
                        return
×
380
                }
381

382
                client.notify(event)
2✔
383
        }
384
}
385

386
// dispatchToClients passes the supplied event to all notification clients that
387
// subscribed to all invoices. Add and settle indices are used to make sure
388
// that clients don't receive duplicate or unwanted events.
389
func (i *InvoiceRegistry) dispatchToClients(event *invoiceEvent) {
2✔
390
        invoice := event.invoice
2✔
391

2✔
392
        clients := i.copyClients()
2✔
393
        for clientID, client := range clients {
4✔
394
                // Before we dispatch this event, we'll check
2✔
395
                // to ensure that this client hasn't already
2✔
396
                // received this notification in order to
2✔
397
                // ensure we don't duplicate any events.
2✔
398

2✔
399
                // TODO(joostjager): Refactor switches.
2✔
400
                state := event.invoice.State
2✔
401
                switch {
2✔
402
                // If we've already sent this settle event to
403
                // the client, then we can skip this.
404
                case state == ContractSettled &&
405
                        client.settleIndex >= invoice.SettleIndex:
×
406
                        continue
×
407

408
                // Similarly, if we've already sent this add to
409
                // the client then we can skip this one, but only if this isn't
410
                // an AMP invoice. AMP invoices always remain in the settle
411
                // state as a base invoice.
412
                case event.setID == nil && state == ContractOpen &&
413
                        client.addIndex >= invoice.AddIndex:
×
414
                        continue
×
415

416
                // These two states should never happen, but we
417
                // log them just in case so we can detect this
418
                // instance.
419
                case state == ContractOpen &&
420
                        client.addIndex+1 != invoice.AddIndex:
2✔
421
                        log.Warnf("client=%v for invoice "+
2✔
422
                                "notifications missed an update, "+
2✔
423
                                "add_index=%v, new add event index=%v",
2✔
424
                                clientID, client.addIndex,
2✔
425
                                invoice.AddIndex)
2✔
426

427
                case state == ContractSettled &&
428
                        client.settleIndex+1 != invoice.SettleIndex:
2✔
429
                        log.Warnf("client=%v for invoice "+
2✔
430
                                "notifications missed an update, "+
2✔
431
                                "settle_index=%v, new settle event index=%v",
2✔
432
                                clientID, client.settleIndex,
2✔
433
                                invoice.SettleIndex)
2✔
434
                }
435

436
                select {
2✔
437
                case <-client.backlogDelivered:
2✔
438
                        // We won't deliver any events until the backlog has
439
                        // been processed.
440
                case <-i.quit:
×
441
                        return
×
442
                }
443

444
                err := client.notify(&invoiceEvent{
2✔
445
                        invoice: invoice,
2✔
446
                        setID:   event.setID,
2✔
447
                })
2✔
448
                if err != nil {
2✔
449
                        log.Errorf("Failed dispatching to client: %v", err)
×
450
                        return
×
451
                }
×
452

453
                // Each time we send a notification to a client, we'll record
454
                // the latest add/settle index it has. We'll use this to ensure
455
                // we don't send a notification twice, which can happen if a new
456
                // event is added while we're catching up a new client.
457
                invState := event.invoice.State
2✔
458
                switch {
2✔
459
                case invState == ContractSettled:
2✔
460
                        client.settleIndex = invoice.SettleIndex
2✔
461

462
                case invState == ContractOpen && event.setID == nil:
2✔
463
                        client.addIndex = invoice.AddIndex
2✔
464

465
                // If this is an AMP invoice, then we'll need to use the set ID
466
                // to keep track of the settle index of the client. AMP
467
                // invoices never go to the open state, but if a setID is
468
                // passed, then we know it was just settled and will track the
469
                // highest settle index so far.
470
                case invState == ContractOpen && event.setID != nil:
2✔
471
                        setID := *event.setID
2✔
472
                        client.settleIndex = invoice.AMPState[setID].SettleIndex
2✔
473

474
                default:
×
475
                        log.Errorf("unexpected invoice state: %v",
×
476
                                event.invoice.State)
×
477
                }
478
        }
479
}
480

481
// deliverBacklogEvents will attempts to query the invoice database for any
482
// notifications that the client has missed since it reconnected last.
483
func (i *InvoiceRegistry) deliverBacklogEvents(ctx context.Context,
484
        client *InvoiceSubscription) error {
2✔
485

2✔
486
        addEvents, err := i.idb.InvoicesAddedSince(ctx, client.addIndex)
2✔
487
        if err != nil {
2✔
488
                return err
×
489
        }
×
490

491
        settleEvents, err := i.idb.InvoicesSettledSince(ctx, client.settleIndex)
2✔
492
        if err != nil {
2✔
493
                return err
×
494
        }
×
495

496
        // If we have any to deliver, then we'll append them to the end of the
497
        // notification queue in order to catch up the client before delivering
498
        // any new notifications.
499
        for _, addEvent := range addEvents {
4✔
500
                // We re-bind the loop variable to ensure we don't hold onto
2✔
501
                // the loop reference causing is to point to the same item.
2✔
502
                addEvent := addEvent
2✔
503

2✔
504
                select {
2✔
505
                case client.ntfnQueue.ChanIn() <- &invoiceEvent{
506
                        invoice: &addEvent,
507
                }:
2✔
508
                case <-i.quit:
×
509
                        return ErrShuttingDown
×
510
                }
511
        }
512

513
        for _, settleEvent := range settleEvents {
4✔
514
                // We re-bind the loop variable to ensure we don't hold onto
2✔
515
                // the loop reference causing is to point to the same item.
2✔
516
                settleEvent := settleEvent
2✔
517

2✔
518
                select {
2✔
519
                case client.ntfnQueue.ChanIn() <- &invoiceEvent{
520
                        invoice: &settleEvent,
521
                }:
2✔
522
                case <-i.quit:
×
523
                        return ErrShuttingDown
×
524
                }
525
        }
526

527
        return nil
2✔
528
}
529

530
// deliverSingleBacklogEvents will attempt to query the invoice database to
531
// retrieve the current invoice state and deliver this to the subscriber. Single
532
// invoice subscribers will always receive the current state right after
533
// subscribing. Only in case the invoice does not yet exist, nothing is sent
534
// yet.
535
func (i *InvoiceRegistry) deliverSingleBacklogEvents(ctx context.Context,
536
        client *SingleInvoiceSubscription) error {
2✔
537

2✔
538
        invoice, err := i.idb.LookupInvoice(ctx, client.invoiceRef)
2✔
539

2✔
540
        // It is possible that the invoice does not exist yet, but the client is
2✔
541
        // already watching it in anticipation.
2✔
542
        isNotFound := errors.Is(err, ErrInvoiceNotFound)
2✔
543
        isNotCreated := errors.Is(err, ErrNoInvoicesCreated)
2✔
544
        if isNotFound || isNotCreated {
4✔
545
                return nil
2✔
546
        }
2✔
547
        if err != nil {
2✔
548
                return err
×
549
        }
×
550

551
        payHash := client.invoiceRef.PayHash()
2✔
552
        if payHash == nil {
2✔
553
                return nil
×
554
        }
×
555

556
        err = client.notify(&invoiceEvent{
2✔
557
                hash:    *payHash,
2✔
558
                invoice: &invoice,
2✔
559
        })
2✔
560
        if err != nil {
2✔
561
                return err
×
562
        }
×
563

564
        log.Debugf("Client(id=%v) delivered single backlog event: payHash=%v",
2✔
565
                client.id, payHash)
2✔
566

2✔
567
        return nil
2✔
568
}
569

570
// AddInvoice adds a regular invoice for the specified amount, identified by
571
// the passed preimage. Additionally, any memo or receipt data provided will
572
// also be stored on-disk. Once this invoice is added, subsystems within the
573
// daemon add/forward HTLCs are able to obtain the proper preimage required for
574
// redemption in the case that we're the final destination. We also return the
575
// addIndex of the newly created invoice which monotonically increases for each
576
// new invoice added.  A side effect of this function is that it also sets
577
// AddIndex on the invoice argument.
578
func (i *InvoiceRegistry) AddInvoice(ctx context.Context, invoice *Invoice,
579
        paymentHash lntypes.Hash) (uint64, error) {
2✔
580

2✔
581
        i.Lock()
2✔
582

2✔
583
        ref := InvoiceRefByHash(paymentHash)
2✔
584
        log.Debugf("Invoice%v: added with terms %v", ref, invoice.Terms)
2✔
585

2✔
586
        addIndex, err := i.idb.AddInvoice(ctx, invoice, paymentHash)
2✔
587
        if err != nil {
4✔
588
                i.Unlock()
2✔
589
                return 0, err
2✔
590
        }
2✔
591

592
        // Now that we've added the invoice, we'll send dispatch a message to
593
        // notify the clients of this new invoice.
594
        i.notifyClients(paymentHash, invoice, nil)
2✔
595
        i.Unlock()
2✔
596

2✔
597
        // InvoiceExpiryWatcher.AddInvoice must not be locked by InvoiceRegistry
2✔
598
        // to avoid deadlock when a new invoice is added while an other is being
2✔
599
        // canceled.
2✔
600
        invoiceExpiryRef := makeInvoiceExpiry(paymentHash, invoice)
2✔
601
        if invoiceExpiryRef != nil {
4✔
602
                i.expiryWatcher.AddInvoices(invoiceExpiryRef)
2✔
603
        }
2✔
604

605
        return addIndex, nil
2✔
606
}
607

608
// LookupInvoice looks up an invoice by its payment hash (R-Hash), if found
609
// then we're able to pull the funds pending within an HTLC.
610
//
611
// TODO(roasbeef): ignore if settled?
612
func (i *InvoiceRegistry) LookupInvoice(ctx context.Context,
613
        rHash lntypes.Hash) (Invoice, error) {
2✔
614

2✔
615
        // We'll check the database to see if there's an existing matching
2✔
616
        // invoice.
2✔
617
        ref := InvoiceRefByHash(rHash)
2✔
618
        return i.idb.LookupInvoice(ctx, ref)
2✔
619
}
2✔
620

621
// LookupInvoiceByRef looks up an invoice by the given reference, if found
622
// then we're able to pull the funds pending within an HTLC.
623
func (i *InvoiceRegistry) LookupInvoiceByRef(ctx context.Context,
624
        ref InvoiceRef) (Invoice, error) {
2✔
625

2✔
626
        return i.idb.LookupInvoice(ctx, ref)
2✔
627
}
2✔
628

629
// startHtlcTimer starts a new timer via the invoice registry main loop that
630
// cancels a single htlc on an invoice when the htlc hold duration has passed.
631
func (i *InvoiceRegistry) startHtlcTimer(invoiceRef InvoiceRef,
632
        key CircuitKey, acceptTime time.Time) error {
2✔
633

2✔
634
        releaseTime := acceptTime.Add(i.cfg.HtlcHoldDuration)
2✔
635
        event := &htlcReleaseEvent{
2✔
636
                invoiceRef:  invoiceRef,
2✔
637
                key:         key,
2✔
638
                releaseTime: releaseTime,
2✔
639
        }
2✔
640

2✔
641
        select {
2✔
642
        case i.htlcAutoReleaseChan <- event:
2✔
643
                return nil
2✔
644

645
        case <-i.quit:
×
646
                return ErrShuttingDown
×
647
        }
648
}
649

650
// cancelSingleHtlc cancels a single accepted htlc on an invoice. It takes
651
// a resolution result which will be used to notify subscribed links and
652
// resolvers of the details of the htlc cancellation.
653
func (i *InvoiceRegistry) cancelSingleHtlc(invoiceRef InvoiceRef,
654
        key CircuitKey, result FailResolutionResult) error {
2✔
655

2✔
656
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
4✔
657
                // Only allow individual htlc cancellation on open invoices.
2✔
658
                if invoice.State != ContractOpen {
4✔
659
                        log.Debugf("cancelSingleHtlc: invoice %v no longer "+
2✔
660
                                "open", invoiceRef)
2✔
661

2✔
662
                        return nil, nil
2✔
663
                }
2✔
664

665
                // Lookup the current status of the htlc in the database.
UNCOV
666
                var (
×
UNCOV
667
                        htlcState HtlcState
×
UNCOV
668
                        setID     *SetID
×
UNCOV
669
                )
×
UNCOV
670
                htlc, ok := invoice.Htlcs[key]
×
UNCOV
671
                if !ok {
×
672
                        // If this is an AMP invoice, then all the HTLCs won't
×
673
                        // be read out, so we'll consult the other mapping to
×
674
                        // try to find the HTLC state in question here.
×
675
                        var found bool
×
676
                        for ampSetID, htlcSet := range invoice.AMPState {
×
677
                                ampSetID := ampSetID
×
678
                                for htlcKey := range htlcSet.InvoiceKeys {
×
679
                                        if htlcKey == key {
×
680
                                                htlcState = htlcSet.State
×
681
                                                setID = &ampSetID
×
682

×
683
                                                found = true
×
684
                                                break
×
685
                                        }
686
                                }
687
                        }
688

689
                        if !found {
×
690
                                return nil, fmt.Errorf("htlc %v not found", key)
×
691
                        }
×
UNCOV
692
                } else {
×
UNCOV
693
                        htlcState = htlc.State
×
UNCOV
694
                }
×
695

696
                // Cancellation is only possible if the htlc wasn't already
697
                // resolved.
UNCOV
698
                if htlcState != HtlcStateAccepted {
×
699
                        log.Debugf("cancelSingleHtlc: htlc %v on invoice %v "+
×
700
                                "is already resolved", key, invoiceRef)
×
701

×
702
                        return nil, nil
×
703
                }
×
704

UNCOV
705
                log.Debugf("cancelSingleHtlc: cancelling htlc %v on invoice %v",
×
UNCOV
706
                        key, invoiceRef)
×
UNCOV
707

×
UNCOV
708
                // Return an update descriptor that cancels htlc and keeps
×
UNCOV
709
                // invoice open.
×
UNCOV
710
                canceledHtlcs := map[CircuitKey]struct{}{
×
UNCOV
711
                        key: {},
×
UNCOV
712
                }
×
UNCOV
713

×
UNCOV
714
                return &InvoiceUpdateDesc{
×
UNCOV
715
                        UpdateType:  CancelHTLCsUpdate,
×
UNCOV
716
                        CancelHtlcs: canceledHtlcs,
×
UNCOV
717
                        SetID:       setID,
×
UNCOV
718
                }, nil
×
719
        }
720

721
        // Try to mark the specified htlc as canceled in the invoice database.
722
        // Intercept the update descriptor to set the local updated variable. If
723
        // no invoice update is performed, we can return early.
724
        setID := (*SetID)(invoiceRef.SetID())
2✔
725
        var updated bool
2✔
726
        invoice, err := i.idb.UpdateInvoice(
2✔
727
                context.Background(), invoiceRef, setID,
2✔
728
                func(invoice *Invoice) (
2✔
729
                        *InvoiceUpdateDesc, error) {
4✔
730

2✔
731
                        updateDesc, err := updateInvoice(invoice)
2✔
732
                        if err != nil {
2✔
733
                                return nil, err
×
734
                        }
×
735
                        updated = updateDesc != nil
2✔
736

2✔
737
                        return updateDesc, err
2✔
738
                },
739
        )
740
        if err != nil {
2✔
741
                return err
×
742
        }
×
743
        if !updated {
4✔
744
                return nil
2✔
745
        }
2✔
746

747
        // The invoice has been updated. Notify subscribers of the htlc
748
        // resolution.
UNCOV
749
        htlc, ok := invoice.Htlcs[key]
×
UNCOV
750
        if !ok {
×
751
                return fmt.Errorf("htlc %v not found", key)
×
752
        }
×
UNCOV
753
        if htlc.State == HtlcStateCanceled {
×
UNCOV
754
                resolution := NewFailResolution(
×
UNCOV
755
                        key, int32(htlc.AcceptHeight), result,
×
UNCOV
756
                )
×
UNCOV
757

×
UNCOV
758
                i.notifyHodlSubscribers(resolution)
×
UNCOV
759
        }
×
UNCOV
760
        return nil
×
761
}
762

763
// processKeySend just-in-time inserts an invoice if this htlc is a keysend
764
// htlc.
765
func (i *InvoiceRegistry) processKeySend(ctx invoiceUpdateCtx) error {
2✔
766
        // Retrieve keysend record if present.
2✔
767
        preimageSlice, ok := ctx.customRecords[record.KeySendType]
2✔
768
        if !ok {
4✔
769
                return nil
2✔
770
        }
2✔
771

772
        // Cancel htlc is preimage is invalid.
773
        preimage, err := lntypes.MakePreimage(preimageSlice)
2✔
774
        if err != nil {
2✔
UNCOV
775
                return err
×
UNCOV
776
        }
×
777
        if preimage.Hash() != ctx.hash {
2✔
778
                return fmt.Errorf("invalid keysend preimage %v for hash %v",
×
779
                        preimage, ctx.hash)
×
780
        }
×
781

782
        // Only allow keysend for non-mpp payments.
783
        if ctx.mpp != nil {
2✔
784
                return errors.New("no mpp keysend supported")
×
785
        }
×
786

787
        // Create an invoice for the htlc amount.
788
        amt := ctx.amtPaid
2✔
789

2✔
790
        // Set tlv required feature vector on the invoice. Otherwise we wouldn't
2✔
791
        // be able to pay to it with keysend.
2✔
792
        rawFeatures := lnwire.NewRawFeatureVector(
2✔
793
                lnwire.TLVOnionPayloadRequired,
2✔
794
        )
2✔
795
        features := lnwire.NewFeatureVector(rawFeatures, lnwire.Features)
2✔
796

2✔
797
        // Use the minimum block delta that we require for settling htlcs.
2✔
798
        finalCltvDelta := i.cfg.FinalCltvRejectDelta
2✔
799

2✔
800
        // Pre-check expiry here to prevent inserting an invoice that will not
2✔
801
        // be settled.
2✔
802
        if ctx.expiry < uint32(ctx.currentHeight+finalCltvDelta) {
2✔
803
                return errors.New("final expiry too soon")
×
804
        }
×
805

806
        // The invoice database indexes all invoices by payment address, however
807
        // legacy keysend payment do not have one. In order to avoid a new
808
        // payment type on-disk wrt. to indexing, we'll continue to insert a
809
        // blank payment address which is special cased in the insertion logic
810
        // to not be indexed. In the future, once AMP is merged, this should be
811
        // replaced by generating a random payment address on the behalf of the
812
        // sender.
813
        payAddr := BlankPayAddr
2✔
814

2✔
815
        // Create placeholder invoice.
2✔
816
        invoice := &Invoice{
2✔
817
                CreationDate: i.cfg.Clock.Now(),
2✔
818
                Terms: ContractTerm{
2✔
819
                        FinalCltvDelta:  finalCltvDelta,
2✔
820
                        Value:           amt,
2✔
821
                        PaymentPreimage: &preimage,
2✔
822
                        PaymentAddr:     payAddr,
2✔
823
                        Features:        features,
2✔
824
                },
2✔
825
        }
2✔
826

2✔
827
        if i.cfg.KeysendHoldTime != 0 {
2✔
UNCOV
828
                invoice.HodlInvoice = true
×
UNCOV
829
                invoice.Terms.Expiry = i.cfg.KeysendHoldTime
×
UNCOV
830
        }
×
831

832
        // Insert invoice into database. Ignore duplicates, because this
833
        // may be a replay.
834
        _, err = i.AddInvoice(context.Background(), invoice, ctx.hash)
2✔
835
        if err != nil && !errors.Is(err, ErrDuplicateInvoice) {
2✔
836
                return err
×
837
        }
×
838

839
        return nil
2✔
840
}
841

842
// processAMP just-in-time inserts an invoice if this htlc is a keysend
843
// htlc.
844
func (i *InvoiceRegistry) processAMP(ctx invoiceUpdateCtx) error {
2✔
845
        // AMP payments MUST also include an MPP record.
2✔
846
        if ctx.mpp == nil {
2✔
UNCOV
847
                return errors.New("no MPP record for AMP")
×
UNCOV
848
        }
×
849

850
        // Create an invoice for the total amount expected, provided in the MPP
851
        // record.
852
        amt := ctx.mpp.TotalMsat()
2✔
853

2✔
854
        // Set the TLV required and MPP optional features on the invoice. We'll
2✔
855
        // also make the AMP features required so that it can't be paid by
2✔
856
        // legacy or MPP htlcs.
2✔
857
        rawFeatures := lnwire.NewRawFeatureVector(
2✔
858
                lnwire.TLVOnionPayloadRequired,
2✔
859
                lnwire.PaymentAddrOptional,
2✔
860
                lnwire.AMPRequired,
2✔
861
        )
2✔
862
        features := lnwire.NewFeatureVector(rawFeatures, lnwire.Features)
2✔
863

2✔
864
        // Use the minimum block delta that we require for settling htlcs.
2✔
865
        finalCltvDelta := i.cfg.FinalCltvRejectDelta
2✔
866

2✔
867
        // Pre-check expiry here to prevent inserting an invoice that will not
2✔
868
        // be settled.
2✔
869
        if ctx.expiry < uint32(ctx.currentHeight+finalCltvDelta) {
2✔
870
                return errors.New("final expiry too soon")
×
871
        }
×
872

873
        // We'll use the sender-generated payment address provided in the HTLC
874
        // to create our AMP invoice.
875
        payAddr := ctx.mpp.PaymentAddr()
2✔
876

2✔
877
        // Create placeholder invoice.
2✔
878
        invoice := &Invoice{
2✔
879
                CreationDate: i.cfg.Clock.Now(),
2✔
880
                Terms: ContractTerm{
2✔
881
                        FinalCltvDelta:  finalCltvDelta,
2✔
882
                        Value:           amt,
2✔
883
                        PaymentPreimage: nil,
2✔
884
                        PaymentAddr:     payAddr,
2✔
885
                        Features:        features,
2✔
886
                },
2✔
887
        }
2✔
888

2✔
889
        // Insert invoice into database. Ignore duplicates payment hashes and
2✔
890
        // payment addrs, this may be a replay or a different HTLC for the AMP
2✔
891
        // invoice.
2✔
892
        _, err := i.AddInvoice(context.Background(), invoice, ctx.hash)
2✔
893
        isDuplicatedInvoice := errors.Is(err, ErrDuplicateInvoice)
2✔
894
        isDuplicatedPayAddr := errors.Is(err, ErrDuplicatePayAddr)
2✔
895
        switch {
2✔
896
        case isDuplicatedInvoice || isDuplicatedPayAddr:
2✔
897
                return nil
2✔
898
        default:
2✔
899
                return err
2✔
900
        }
901
}
902

903
// NotifyExitHopHtlc attempts to mark an invoice as settled. The return value
904
// describes how the htlc should be resolved.
905
//
906
// When the preimage of the invoice is not yet known (hodl invoice), this
907
// function moves the invoice to the accepted state. When SettleHoldInvoice is
908
// called later, a resolution message will be send back to the caller via the
909
// provided hodlChan. Invoice registry sends on this channel what action needs
910
// to be taken on the htlc (settle or cancel). The caller needs to ensure that
911
// the channel is either buffered or received on from another goroutine to
912
// prevent deadlock.
913
//
914
// In the case that the htlc is part of a larger set of htlcs that pay to the
915
// same invoice (multi-path payment), the htlc is held until the set is
916
// complete. If the set doesn't fully arrive in time, a timer will cancel the
917
// held htlc.
918
func (i *InvoiceRegistry) NotifyExitHopHtlc(rHash lntypes.Hash,
919
        amtPaid lnwire.MilliSatoshi, expiry uint32, currentHeight int32,
920
        circuitKey CircuitKey, hodlChan chan<- interface{},
921
        wireCustomRecords lnwire.CustomRecords,
922
        payload Payload) (HtlcResolution, error) {
2✔
923

2✔
924
        // Create the update context containing the relevant details of the
2✔
925
        // incoming htlc.
2✔
926
        ctx := invoiceUpdateCtx{
2✔
927
                hash:                 rHash,
2✔
928
                circuitKey:           circuitKey,
2✔
929
                amtPaid:              amtPaid,
2✔
930
                expiry:               expiry,
2✔
931
                currentHeight:        currentHeight,
2✔
932
                finalCltvRejectDelta: i.cfg.FinalCltvRejectDelta,
2✔
933
                wireCustomRecords:    wireCustomRecords,
2✔
934
                customRecords:        payload.CustomRecords(),
2✔
935
                mpp:                  payload.MultiPath(),
2✔
936
                amp:                  payload.AMPRecord(),
2✔
937
                metadata:             payload.Metadata(),
2✔
938
                pathID:               payload.PathID(),
2✔
939
                totalAmtMsat:         payload.TotalAmtMsat(),
2✔
940
        }
2✔
941

2✔
942
        switch {
2✔
943
        // If we are accepting spontaneous AMP payments and this payload
944
        // contains an AMP record, create an AMP invoice that will be settled
945
        // below.
946
        case i.cfg.AcceptAMP && ctx.amp != nil:
2✔
947
                err := i.processAMP(ctx)
2✔
948
                if err != nil {
2✔
UNCOV
949
                        ctx.log(fmt.Sprintf("amp error: %v", err))
×
UNCOV
950

×
UNCOV
951
                        return NewFailResolution(
×
UNCOV
952
                                circuitKey, currentHeight, ResultAmpError,
×
UNCOV
953
                        ), nil
×
UNCOV
954
                }
×
955

956
        // If we are accepting spontaneous keysend payments, create a regular
957
        // invoice that will be settled below. We also enforce that this is only
958
        // done when no AMP payload is present since it will only be settle-able
959
        // by regular HTLCs.
960
        case i.cfg.AcceptKeySend && ctx.amp == nil:
2✔
961
                err := i.processKeySend(ctx)
2✔
962
                if err != nil {
2✔
UNCOV
963
                        ctx.log(fmt.Sprintf("keysend error: %v", err))
×
UNCOV
964

×
UNCOV
965
                        return NewFailResolution(
×
UNCOV
966
                                circuitKey, currentHeight, ResultKeySendError,
×
UNCOV
967
                        ), nil
×
UNCOV
968
                }
×
969
        }
970

971
        // Execute locked notify exit hop logic.
972
        i.Lock()
2✔
973
        resolution, invoiceToExpire, err := i.notifyExitHopHtlcLocked(
2✔
974
                &ctx, hodlChan,
2✔
975
        )
2✔
976
        i.Unlock()
2✔
977
        if err != nil {
4✔
978
                return nil, err
2✔
979
        }
2✔
980

981
        if invoiceToExpire != nil {
4✔
982
                i.expiryWatcher.AddInvoices(invoiceToExpire)
2✔
983
        }
2✔
984

985
        switch r := resolution.(type) {
2✔
986
        // The htlc is held. Start a timer outside the lock if the htlc should
987
        // be auto-released, because otherwise a deadlock may happen with the
988
        // main event loop.
989
        case *htlcAcceptResolution:
2✔
990
                if r.autoRelease {
4✔
991
                        var invRef InvoiceRef
2✔
992
                        if ctx.amp != nil {
4✔
993
                                invRef = InvoiceRefBySetID(*ctx.setID())
2✔
994
                        } else {
4✔
995
                                invRef = ctx.invoiceRef()
2✔
996
                        }
2✔
997

998
                        err := i.startHtlcTimer(
2✔
999
                                invRef, circuitKey, r.acceptTime,
2✔
1000
                        )
2✔
1001
                        if err != nil {
2✔
1002
                                return nil, err
×
1003
                        }
×
1004
                }
1005

1006
                // We return a nil resolution because htlc acceptances are
1007
                // represented as nil resolutions externally.
1008
                // TODO(carla) update calling code to handle accept resolutions.
1009
                return nil, nil
2✔
1010

1011
        // A direct resolution was received for this htlc.
1012
        case HtlcResolution:
2✔
1013
                return r, nil
2✔
1014

1015
        // Fail if an unknown resolution type was received.
1016
        default:
×
1017
                return nil, errors.New("invalid resolution type")
×
1018
        }
1019
}
1020

1021
// notifyExitHopHtlcLocked is the internal implementation of NotifyExitHopHtlc
1022
// that should be executed inside the registry lock. The returned invoiceExpiry
1023
// (if not nil) needs to be added to the expiry watcher outside of the lock.
1024
func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
1025
        ctx *invoiceUpdateCtx, hodlChan chan<- interface{}) (
1026
        HtlcResolution, invoiceExpiry, error) {
2✔
1027

2✔
1028
        invoiceRef := ctx.invoiceRef()
2✔
1029
        setID := (*SetID)(ctx.setID())
2✔
1030

2✔
1031
        // We need to look up the current state of the invoice in order to send
2✔
1032
        // the previously accepted/settled HTLCs to the interceptor.
2✔
1033
        existingInvoice, err := i.idb.LookupInvoice(
2✔
1034
                context.Background(), invoiceRef,
2✔
1035
        )
2✔
1036
        switch {
2✔
1037
        case errors.Is(err, ErrInvoiceNotFound) ||
1038
                errors.Is(err, ErrNoInvoicesCreated):
2✔
1039

2✔
1040
                // If the invoice was not found, return a failure resolution
2✔
1041
                // with an invoice not found result.
2✔
1042
                return NewFailResolution(
2✔
1043
                        ctx.circuitKey, ctx.currentHeight,
2✔
1044
                        ResultInvoiceNotFound,
2✔
1045
                ), nil, nil
2✔
1046

1047
        case err != nil:
×
1048
                ctx.log(err.Error())
×
1049
                return nil, nil, err
×
1050
        }
1051

1052
        // Provide the invoice to the settlement interceptor to allow
1053
        // the interceptor's client an opportunity to manipulate the
1054
        // settlement process.
1055
        err = i.cfg.HtlcInterceptor.Intercept(HtlcModifyRequest{
2✔
1056
                WireCustomRecords:  ctx.wireCustomRecords,
2✔
1057
                ExitHtlcCircuitKey: ctx.circuitKey,
2✔
1058
                ExitHtlcAmt:        ctx.amtPaid,
2✔
1059
                ExitHtlcExpiry:     ctx.expiry,
2✔
1060
                CurrentHeight:      uint32(ctx.currentHeight),
2✔
1061
                Invoice:            existingInvoice,
2✔
1062
        }, func(resp HtlcModifyResponse) {
4✔
1063
                log.Debugf("Received invoice HTLC interceptor response: %v",
2✔
1064
                        resp)
2✔
1065

2✔
1066
                if resp.AmountPaid != 0 {
4✔
1067
                        ctx.amtPaid = resp.AmountPaid
2✔
1068
                }
2✔
1069
        })
1070
        if err != nil {
4✔
1071
                err := fmt.Errorf("error during invoice HTLC interception: %w",
2✔
1072
                        err)
2✔
1073
                ctx.log(err.Error())
2✔
1074

2✔
1075
                return nil, nil, err
2✔
1076
        }
2✔
1077

1078
        // We'll attempt to settle an invoice matching this rHash on disk (if
1079
        // one exists). The callback will update the invoice state and/or htlcs.
1080
        var (
2✔
1081
                resolution        HtlcResolution
2✔
1082
                updateSubscribers bool
2✔
1083
        )
2✔
1084
        callback := func(inv *Invoice) (*InvoiceUpdateDesc, error) {
4✔
1085
                updateDesc, res, err := updateInvoice(ctx, inv)
2✔
1086
                if err != nil {
2✔
1087
                        return nil, err
×
1088
                }
×
1089

1090
                // Only send an update if the invoice state was changed.
1091
                updateSubscribers = updateDesc != nil &&
2✔
1092
                        updateDesc.State != nil
2✔
1093

2✔
1094
                // Assign resolution to outer scope variable.
2✔
1095
                resolution = res
2✔
1096

2✔
1097
                return updateDesc, nil
2✔
1098
        }
1099

1100
        invoice, err := i.idb.UpdateInvoice(
2✔
1101
                context.Background(), invoiceRef, setID, callback,
2✔
1102
        )
2✔
1103

2✔
1104
        var duplicateSetIDErr ErrDuplicateSetID
2✔
1105
        if errors.As(err, &duplicateSetIDErr) {
2✔
1106
                return NewFailResolution(
×
1107
                        ctx.circuitKey, ctx.currentHeight,
×
1108
                        ResultInvoiceNotFound,
×
1109
                ), nil, nil
×
1110
        }
×
1111

1112
        switch {
2✔
1113
        case errors.Is(err, ErrInvoiceNotFound):
×
1114
                // If the invoice was not found, return a failure resolution
×
1115
                // with an invoice not found result.
×
1116
                return NewFailResolution(
×
1117
                        ctx.circuitKey, ctx.currentHeight,
×
1118
                        ResultInvoiceNotFound,
×
1119
                ), nil, nil
×
1120

1121
        case errors.Is(err, ErrInvRefEquivocation):
×
1122
                return NewFailResolution(
×
1123
                        ctx.circuitKey, ctx.currentHeight,
×
1124
                        ResultInvoiceNotFound,
×
1125
                ), nil, nil
×
1126

1127
        case err == nil:
2✔
1128

1129
        default:
×
1130
                ctx.log(err.Error())
×
1131
                return nil, nil, err
×
1132
        }
1133

1134
        var invoiceToExpire invoiceExpiry
2✔
1135

2✔
1136
        log.Tracef("Settlement resolution: %T %v", resolution, resolution)
2✔
1137

2✔
1138
        switch res := resolution.(type) {
2✔
1139
        case *HtlcFailResolution:
2✔
1140
                // Inspect latest htlc state on the invoice. If it is found,
2✔
1141
                // we will update the accept height as it was recorded in the
2✔
1142
                // invoice database (which occurs in the case where the htlc
2✔
1143
                // reached the database in a previous call). If the htlc was
2✔
1144
                // not found on the invoice, it was immediately failed so we
2✔
1145
                // send the failure resolution as is, which has the current
2✔
1146
                // height set as the accept height.
2✔
1147
                invoiceHtlc, ok := invoice.Htlcs[ctx.circuitKey]
2✔
1148
                if ok {
4✔
1149
                        res.AcceptHeight = int32(invoiceHtlc.AcceptHeight)
2✔
1150
                }
2✔
1151

1152
                ctx.log(fmt.Sprintf("failure resolution result "+
2✔
1153
                        "outcome: %v, at accept height: %v",
2✔
1154
                        res.Outcome, res.AcceptHeight))
2✔
1155

2✔
1156
                // Some failures apply to the entire HTLC set. Break here if
2✔
1157
                // this isn't one of them.
2✔
1158
                if !res.Outcome.IsSetFailure() {
4✔
1159
                        break
2✔
1160
                }
1161

1162
                // Also cancel any HTLCs in the HTLC set that are also in the
1163
                // canceled state with the same failure result.
UNCOV
1164
                setID := ctx.setID()
×
UNCOV
1165
                canceledHtlcSet := invoice.HTLCSet(setID, HtlcStateCanceled)
×
UNCOV
1166
                for key, htlc := range canceledHtlcSet {
×
UNCOV
1167
                        htlcFailResolution := NewFailResolution(
×
UNCOV
1168
                                key, int32(htlc.AcceptHeight), res.Outcome,
×
UNCOV
1169
                        )
×
UNCOV
1170

×
UNCOV
1171
                        i.notifyHodlSubscribers(htlcFailResolution)
×
UNCOV
1172
                }
×
1173

1174
        // If the htlc was settled, we will settle any previously accepted
1175
        // htlcs and notify our peer to settle them.
1176
        case *HtlcSettleResolution:
2✔
1177
                ctx.log(fmt.Sprintf("settle resolution result "+
2✔
1178
                        "outcome: %v, at accept height: %v",
2✔
1179
                        res.Outcome, res.AcceptHeight))
2✔
1180

2✔
1181
                // Also settle any previously accepted htlcs. If a htlc is
2✔
1182
                // marked as settled, we should follow now and settle the htlc
2✔
1183
                // with our peer.
2✔
1184
                setID := ctx.setID()
2✔
1185
                settledHtlcSet := invoice.HTLCSet(setID, HtlcStateSettled)
2✔
1186
                for key, htlc := range settledHtlcSet {
4✔
1187
                        preimage := res.Preimage
2✔
1188
                        if htlc.AMP != nil && htlc.AMP.Preimage != nil {
4✔
1189
                                preimage = *htlc.AMP.Preimage
2✔
1190
                        }
2✔
1191

1192
                        // Notify subscribers that the htlcs should be settled
1193
                        // with our peer. Note that the outcome of the
1194
                        // resolution is set based on the outcome of the single
1195
                        // htlc that we just settled, so may not be accurate
1196
                        // for all htlcs.
1197
                        htlcSettleResolution := NewSettleResolution(
2✔
1198
                                preimage, key,
2✔
1199
                                int32(htlc.AcceptHeight), res.Outcome,
2✔
1200
                        )
2✔
1201

2✔
1202
                        // Notify subscribers that the htlc should be settled
2✔
1203
                        // with our peer.
2✔
1204
                        i.notifyHodlSubscribers(htlcSettleResolution)
2✔
1205
                }
1206

1207
                // If concurrent payments were attempted to this invoice before
1208
                // the current one was ultimately settled, cancel back any of
1209
                // the HTLCs immediately. As a result of the settle, the HTLCs
1210
                // in other HTLC sets are automatically converted to a canceled
1211
                // state when updating the invoice.
1212
                //
1213
                // TODO(roasbeef): can remove now??
1214
                canceledHtlcSet := invoice.HTLCSetCompliment(
2✔
1215
                        setID, HtlcStateCanceled,
2✔
1216
                )
2✔
1217
                for key, htlc := range canceledHtlcSet {
2✔
1218
                        htlcFailResolution := NewFailResolution(
×
1219
                                key, int32(htlc.AcceptHeight),
×
1220
                                ResultInvoiceAlreadySettled,
×
1221
                        )
×
1222

×
1223
                        i.notifyHodlSubscribers(htlcFailResolution)
×
1224
                }
×
1225

1226
        // If we accepted the htlc, subscribe to the hodl invoice and return
1227
        // an accept resolution with the htlc's accept time on it.
1228
        case *htlcAcceptResolution:
2✔
1229
                invoiceHtlc, ok := invoice.Htlcs[ctx.circuitKey]
2✔
1230
                if !ok {
2✔
1231
                        return nil, nil, fmt.Errorf("accepted htlc: %v not"+
×
1232
                                " present on invoice: %x", ctx.circuitKey,
×
1233
                                ctx.hash[:])
×
1234
                }
×
1235

1236
                // Determine accepted height of this htlc. If the htlc reached
1237
                // the invoice database (possibly in a previous call to the
1238
                // invoice registry), we'll take the original accepted height
1239
                // as it was recorded in the database.
1240
                acceptHeight := int32(invoiceHtlc.AcceptHeight)
2✔
1241

2✔
1242
                ctx.log(fmt.Sprintf("accept resolution result "+
2✔
1243
                        "outcome: %v, at accept height: %v",
2✔
1244
                        res.outcome, acceptHeight))
2✔
1245

2✔
1246
                // Auto-release the htlc if the invoice is still open. It can
2✔
1247
                // only happen for mpp payments that there are htlcs in state
2✔
1248
                // Accepted while the invoice is Open.
2✔
1249
                if invoice.State == ContractOpen {
4✔
1250
                        res.acceptTime = invoiceHtlc.AcceptTime
2✔
1251
                        res.autoRelease = true
2✔
1252
                }
2✔
1253

1254
                // If we have fully accepted the set of htlcs for this invoice,
1255
                // we can now add it to our invoice expiry watcher. We do not
1256
                // add invoices before they are fully accepted, because it is
1257
                // possible that we MppTimeout the htlcs, and then our relevant
1258
                // expiry height could change.
1259
                if res.outcome == resultAccepted {
4✔
1260
                        invoiceToExpire = makeInvoiceExpiry(ctx.hash, invoice)
2✔
1261
                }
2✔
1262

1263
                i.hodlSubscribe(hodlChan, ctx.circuitKey)
2✔
1264

1265
        default:
×
1266
                panic("unknown action")
×
1267
        }
1268

1269
        // Now that the links have been notified of any state changes to their
1270
        // HTLCs, we'll go ahead and notify any clients waiting on the invoice
1271
        // state changes.
1272
        if updateSubscribers {
4✔
1273
                // We'll add a setID onto the notification, but only if this is
2✔
1274
                // an AMP invoice being settled.
2✔
1275
                var setID *[32]byte
2✔
1276
                if _, ok := resolution.(*HtlcSettleResolution); ok {
4✔
1277
                        setID = ctx.setID()
2✔
1278
                }
2✔
1279

1280
                i.notifyClients(ctx.hash, invoice, setID)
2✔
1281
        }
1282

1283
        return resolution, invoiceToExpire, nil
2✔
1284
}
1285

1286
// SettleHodlInvoice sets the preimage of a hodl invoice.
1287
func (i *InvoiceRegistry) SettleHodlInvoice(ctx context.Context,
1288
        preimage lntypes.Preimage) error {
2✔
1289

2✔
1290
        i.Lock()
2✔
1291
        defer i.Unlock()
2✔
1292

2✔
1293
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
4✔
1294
                switch invoice.State {
2✔
1295
                case ContractOpen:
×
1296
                        return nil, ErrInvoiceStillOpen
×
1297

1298
                case ContractCanceled:
×
1299
                        return nil, ErrInvoiceAlreadyCanceled
×
1300

UNCOV
1301
                case ContractSettled:
×
UNCOV
1302
                        return nil, ErrInvoiceAlreadySettled
×
1303
                }
1304

1305
                return &InvoiceUpdateDesc{
2✔
1306
                        UpdateType: SettleHodlInvoiceUpdate,
2✔
1307
                        State: &InvoiceStateUpdateDesc{
2✔
1308
                                NewState: ContractSettled,
2✔
1309
                                Preimage: &preimage,
2✔
1310
                        },
2✔
1311
                }, nil
2✔
1312
        }
1313

1314
        hash := preimage.Hash()
2✔
1315
        invoiceRef := InvoiceRefByHash(hash)
2✔
1316
        invoice, err := i.idb.UpdateInvoice(ctx, invoiceRef, nil, updateInvoice)
2✔
1317
        if err != nil {
2✔
UNCOV
1318
                log.Errorf("SettleHodlInvoice with preimage %v: %v",
×
UNCOV
1319
                        preimage, err)
×
UNCOV
1320

×
UNCOV
1321
                return err
×
UNCOV
1322
        }
×
1323

1324
        log.Debugf("Invoice%v: settled with preimage %v", invoiceRef,
2✔
1325
                invoice.Terms.PaymentPreimage)
2✔
1326

2✔
1327
        // In the callback, we marked the invoice as settled. UpdateInvoice will
2✔
1328
        // have seen this and should have moved all htlcs that were accepted to
2✔
1329
        // the settled state. In the loop below, we go through all of these and
2✔
1330
        // notify links and resolvers that are waiting for resolution. Any htlcs
2✔
1331
        // that were already settled before, will be notified again. This isn't
2✔
1332
        // necessary but doesn't hurt either.
2✔
1333
        for key, htlc := range invoice.Htlcs {
4✔
1334
                if htlc.State != HtlcStateSettled {
2✔
1335
                        continue
×
1336
                }
1337

1338
                resolution := NewSettleResolution(
2✔
1339
                        preimage, key, int32(htlc.AcceptHeight), ResultSettled,
2✔
1340
                )
2✔
1341

2✔
1342
                i.notifyHodlSubscribers(resolution)
2✔
1343
        }
1344
        i.notifyClients(hash, invoice, nil)
2✔
1345

2✔
1346
        return nil
2✔
1347
}
1348

1349
// CancelInvoice attempts to cancel the invoice corresponding to the passed
1350
// payment hash.
1351
func (i *InvoiceRegistry) CancelInvoice(ctx context.Context,
1352
        payHash lntypes.Hash) error {
2✔
1353

2✔
1354
        return i.cancelInvoiceImpl(ctx, payHash, true)
2✔
1355
}
2✔
1356

1357
// shouldCancel examines the state of an invoice and whether we want to
1358
// cancel already accepted invoices, taking our force cancel boolean into
1359
// account. This is pulled out into its own function so that tests that mock
1360
// cancelInvoiceImpl can reuse this logic.
1361
func shouldCancel(state ContractState, cancelAccepted bool) bool {
2✔
1362
        if state != ContractAccepted {
4✔
1363
                return true
2✔
1364
        }
2✔
1365

1366
        // If the invoice is accepted, we should only cancel if we want to
1367
        // force cancellation of accepted invoices.
1368
        return cancelAccepted
2✔
1369
}
1370

1371
// cancelInvoice attempts to cancel the invoice corresponding to the passed
1372
// payment hash. Accepted invoices will only be canceled if explicitly
1373
// requested to do so. It notifies subscribing links and resolvers that
1374
// the associated htlcs were canceled if they change state.
1375
func (i *InvoiceRegistry) cancelInvoiceImpl(ctx context.Context,
1376
        payHash lntypes.Hash, cancelAccepted bool) error {
2✔
1377

2✔
1378
        i.Lock()
2✔
1379
        defer i.Unlock()
2✔
1380

2✔
1381
        ref := InvoiceRefByHash(payHash)
2✔
1382
        log.Debugf("Invoice%v: canceling invoice", ref)
2✔
1383

2✔
1384
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
4✔
1385
                if !shouldCancel(invoice.State, cancelAccepted) {
2✔
UNCOV
1386
                        return nil, nil
×
UNCOV
1387
                }
×
1388

1389
                // Move invoice to the canceled state. Rely on validation in
1390
                // channeldb to return an error if the invoice is already
1391
                // settled or canceled.
1392
                return &InvoiceUpdateDesc{
2✔
1393
                        UpdateType: CancelInvoiceUpdate,
2✔
1394
                        State: &InvoiceStateUpdateDesc{
2✔
1395
                                NewState: ContractCanceled,
2✔
1396
                        },
2✔
1397
                }, nil
2✔
1398
        }
1399

1400
        invoiceRef := InvoiceRefByHash(payHash)
2✔
1401
        invoice, err := i.idb.UpdateInvoice(ctx, invoiceRef, nil, updateInvoice)
2✔
1402

2✔
1403
        // Implement idempotency by returning success if the invoice was already
2✔
1404
        // canceled.
2✔
1405
        if errors.Is(err, ErrInvoiceAlreadyCanceled) {
2✔
UNCOV
1406
                log.Debugf("Invoice%v: already canceled", ref)
×
UNCOV
1407
                return nil
×
UNCOV
1408
        }
×
1409
        if err != nil {
4✔
1410
                return err
2✔
1411
        }
2✔
1412

1413
        // Return without cancellation if the invoice state is ContractAccepted.
1414
        if invoice.State == ContractAccepted {
2✔
UNCOV
1415
                log.Debugf("Invoice%v: remains accepted as cancel wasn't"+
×
UNCOV
1416
                        "explicitly requested.", ref)
×
UNCOV
1417
                return nil
×
UNCOV
1418
        }
×
1419

1420
        log.Debugf("Invoice%v: canceled", ref)
2✔
1421

2✔
1422
        // In the callback, some htlcs may have been moved to the canceled
2✔
1423
        // state. We now go through all of these and notify links and resolvers
2✔
1424
        // that are waiting for resolution. Any htlcs that were already canceled
2✔
1425
        // before, will be notified again. This isn't necessary but doesn't hurt
2✔
1426
        // either.
2✔
1427
        for key, htlc := range invoice.Htlcs {
4✔
1428
                if htlc.State != HtlcStateCanceled {
2✔
1429
                        continue
×
1430
                }
1431

1432
                i.notifyHodlSubscribers(
2✔
1433
                        NewFailResolution(
2✔
1434
                                key, int32(htlc.AcceptHeight), ResultCanceled,
2✔
1435
                        ),
2✔
1436
                )
2✔
1437
        }
1438
        i.notifyClients(payHash, invoice, nil)
2✔
1439

2✔
1440
        // Attempt to also delete the invoice if requested through the registry
2✔
1441
        // config.
2✔
1442
        if i.cfg.GcCanceledInvoicesOnTheFly {
2✔
UNCOV
1443
                // Assemble the delete reference and attempt to delete through
×
UNCOV
1444
                // the invocice from the DB.
×
UNCOV
1445
                deleteRef := InvoiceDeleteRef{
×
UNCOV
1446
                        PayHash:     payHash,
×
UNCOV
1447
                        AddIndex:    invoice.AddIndex,
×
UNCOV
1448
                        SettleIndex: invoice.SettleIndex,
×
UNCOV
1449
                }
×
UNCOV
1450
                if invoice.Terms.PaymentAddr != BlankPayAddr {
×
1451
                        deleteRef.PayAddr = &invoice.Terms.PaymentAddr
×
1452
                }
×
1453

UNCOV
1454
                err = i.idb.DeleteInvoice(ctx, []InvoiceDeleteRef{deleteRef})
×
UNCOV
1455
                // If by any chance deletion failed, then log it instead of
×
UNCOV
1456
                // returning the error, as the invoice itself has already been
×
UNCOV
1457
                // canceled.
×
UNCOV
1458
                if err != nil {
×
1459
                        log.Warnf("Invoice %v could not be deleted: %v", ref,
×
1460
                                err)
×
1461
                }
×
1462
        }
1463

1464
        return nil
2✔
1465
}
1466

1467
// notifyClients notifies all currently registered invoice notification clients
1468
// of a newly added/settled invoice.
1469
func (i *InvoiceRegistry) notifyClients(hash lntypes.Hash,
1470
        invoice *Invoice, setID *[32]byte) {
2✔
1471

2✔
1472
        event := &invoiceEvent{
2✔
1473
                invoice: invoice,
2✔
1474
                hash:    hash,
2✔
1475
                setID:   setID,
2✔
1476
        }
2✔
1477

2✔
1478
        select {
2✔
1479
        case i.invoiceEvents <- event:
2✔
1480
        case <-i.quit:
×
1481
        }
1482
}
1483

1484
// invoiceSubscriptionKit defines that are common to both all invoice
1485
// subscribers and single invoice subscribers.
1486
type invoiceSubscriptionKit struct {
1487
        id uint32 // nolint:structcheck
1488

1489
        // quit is a chan mouted to InvoiceRegistry that signals a shutdown.
1490
        quit chan struct{}
1491

1492
        ntfnQueue *queue.ConcurrentQueue
1493

1494
        canceled   uint32 // To be used atomically.
1495
        cancelChan chan struct{}
1496

1497
        // backlogDelivered is closed when the backlog events have been
1498
        // delivered.
1499
        backlogDelivered chan struct{}
1500
}
1501

1502
// InvoiceSubscription represents an intent to receive updates for newly added
1503
// or settled invoices. For each newly added invoice, a copy of the invoice
1504
// will be sent over the NewInvoices channel. Similarly, for each newly settled
1505
// invoice, a copy of the invoice will be sent over the SettledInvoices
1506
// channel.
1507
type InvoiceSubscription struct {
1508
        invoiceSubscriptionKit
1509

1510
        // NewInvoices is a channel that we'll use to send all newly created
1511
        // invoices with an invoice index greater than the specified
1512
        // StartingInvoiceIndex field.
1513
        NewInvoices chan *Invoice
1514

1515
        // SettledInvoices is a channel that we'll use to send all settled
1516
        // invoices with an invoices index greater than the specified
1517
        // StartingInvoiceIndex field.
1518
        SettledInvoices chan *Invoice
1519

1520
        // addIndex is the highest add index the caller knows of. We'll use
1521
        // this information to send out an event backlog to the notifications
1522
        // subscriber. Any new add events with an index greater than this will
1523
        // be dispatched before any new notifications are sent out.
1524
        addIndex uint64
1525

1526
        // settleIndex is the highest settle index the caller knows of. We'll
1527
        // use this information to send out an event backlog to the
1528
        // notifications subscriber. Any new settle events with an index
1529
        // greater than this will be dispatched before any new notifications
1530
        // are sent out.
1531
        settleIndex uint64
1532
}
1533

1534
// SingleInvoiceSubscription represents an intent to receive updates for a
1535
// specific invoice.
1536
type SingleInvoiceSubscription struct {
1537
        invoiceSubscriptionKit
1538

1539
        invoiceRef InvoiceRef
1540

1541
        // Updates is a channel that we'll use to send all invoice events for
1542
        // the invoice that is subscribed to.
1543
        Updates chan *Invoice
1544
}
1545

1546
// PayHash returns the optional payment hash of the target invoice.
1547
//
1548
// TODO(positiveblue): This method is only supposed to be used in tests. It will
1549
// be deleted as soon as invoiceregistery_test is in the same module.
UNCOV
1550
func (s *SingleInvoiceSubscription) PayHash() *lntypes.Hash {
×
UNCOV
1551
        return s.invoiceRef.PayHash()
×
UNCOV
1552
}
×
1553

1554
// Cancel unregisters the InvoiceSubscription, freeing any previously allocated
1555
// resources.
1556
func (i *invoiceSubscriptionKit) Cancel() {
2✔
1557
        if !atomic.CompareAndSwapUint32(&i.canceled, 0, 1) {
2✔
1558
                return
×
1559
        }
×
1560

1561
        i.ntfnQueue.Stop()
2✔
1562
        close(i.cancelChan)
2✔
1563
}
1564

1565
func (i *invoiceSubscriptionKit) notify(event *invoiceEvent) error {
2✔
1566
        select {
2✔
1567
        case i.ntfnQueue.ChanIn() <- event:
2✔
1568

1569
        case <-i.cancelChan:
×
1570
                // This can only be triggered by delivery of non-backlog
×
1571
                // events.
×
1572
                return ErrShuttingDown
×
1573
        case <-i.quit:
×
1574
                return ErrShuttingDown
×
1575
        }
1576

1577
        return nil
2✔
1578
}
1579

1580
// SubscribeNotifications returns an InvoiceSubscription which allows the
1581
// caller to receive async notifications when any invoices are settled or
1582
// added. The invoiceIndex parameter is a streaming "checkpoint". We'll start
1583
// by first sending out all new events with an invoice index _greater_ than
1584
// this value. Afterwards, we'll send out real-time notifications.
1585
func (i *InvoiceRegistry) SubscribeNotifications(ctx context.Context,
1586
        addIndex, settleIndex uint64) (*InvoiceSubscription, error) {
2✔
1587

2✔
1588
        client := &InvoiceSubscription{
2✔
1589
                NewInvoices:     make(chan *Invoice),
2✔
1590
                SettledInvoices: make(chan *Invoice),
2✔
1591
                addIndex:        addIndex,
2✔
1592
                settleIndex:     settleIndex,
2✔
1593
                invoiceSubscriptionKit: invoiceSubscriptionKit{
2✔
1594
                        quit:             i.quit,
2✔
1595
                        ntfnQueue:        queue.NewConcurrentQueue(20),
2✔
1596
                        cancelChan:       make(chan struct{}),
2✔
1597
                        backlogDelivered: make(chan struct{}),
2✔
1598
                },
2✔
1599
        }
2✔
1600
        client.ntfnQueue.Start()
2✔
1601

2✔
1602
        // This notifies other goroutines that the backlog phase is over.
2✔
1603
        defer close(client.backlogDelivered)
2✔
1604

2✔
1605
        // Always increment by 1 first, and our client ID will start with 1,
2✔
1606
        // not 0.
2✔
1607
        client.id = atomic.AddUint32(&i.nextClientID, 1)
2✔
1608

2✔
1609
        // Before we register this new invoice subscription, we'll launch a new
2✔
1610
        // goroutine that will proxy all notifications appended to the end of
2✔
1611
        // the concurrent queue to the two client-side channels the caller will
2✔
1612
        // feed off of.
2✔
1613
        i.wg.Add(1)
2✔
1614
        go func() {
4✔
1615
                defer i.wg.Done()
2✔
1616
                defer i.deleteClient(client.id)
2✔
1617

2✔
1618
                for {
4✔
1619
                        select {
2✔
1620
                        // A new invoice event has been sent by the
1621
                        // invoiceRegistry! We'll figure out if this is an add
1622
                        // event or a settle event, then dispatch the event to
1623
                        // the client.
1624
                        case ntfn := <-client.ntfnQueue.ChanOut():
2✔
1625
                                invoiceEvent := ntfn.(*invoiceEvent)
2✔
1626

2✔
1627
                                var targetChan chan *Invoice
2✔
1628
                                state := invoiceEvent.invoice.State
2✔
1629
                                switch {
2✔
1630
                                // AMP invoices never move to settled, but will
1631
                                // be sent with a set ID if an HTLC set is
1632
                                // being settled.
1633
                                case state == ContractOpen &&
1634
                                        invoiceEvent.setID != nil:
2✔
1635
                                        fallthrough
2✔
1636

1637
                                case state == ContractSettled:
2✔
1638
                                        targetChan = client.SettledInvoices
2✔
1639

1640
                                case state == ContractOpen:
2✔
1641
                                        targetChan = client.NewInvoices
2✔
1642

1643
                                default:
×
1644
                                        log.Errorf("unknown invoice state: %v",
×
1645
                                                state)
×
1646

×
1647
                                        continue
×
1648
                                }
1649

1650
                                select {
2✔
1651
                                case targetChan <- invoiceEvent.invoice:
2✔
1652

1653
                                case <-client.cancelChan:
×
1654
                                        return
×
1655

1656
                                case <-i.quit:
×
1657
                                        return
×
1658
                                }
1659

1660
                        case <-client.cancelChan:
2✔
1661
                                return
2✔
1662

UNCOV
1663
                        case <-i.quit:
×
UNCOV
1664
                                return
×
1665
                        }
1666
                }
1667
        }()
1668

1669
        i.notificationClientMux.Lock()
2✔
1670
        i.notificationClients[client.id] = client
2✔
1671
        i.notificationClientMux.Unlock()
2✔
1672

2✔
1673
        // Query the database to see if based on the provided addIndex and
2✔
1674
        // settledIndex we need to deliver any backlog notifications.
2✔
1675
        err := i.deliverBacklogEvents(ctx, client)
2✔
1676
        if err != nil {
2✔
1677
                return nil, err
×
1678
        }
×
1679

1680
        log.Infof("New invoice subscription client: id=%v", client.id)
2✔
1681

2✔
1682
        return client, nil
2✔
1683
}
1684

1685
// SubscribeSingleInvoice returns an SingleInvoiceSubscription which allows the
1686
// caller to receive async notifications for a specific invoice.
1687
func (i *InvoiceRegistry) SubscribeSingleInvoice(ctx context.Context,
1688
        hash lntypes.Hash) (*SingleInvoiceSubscription, error) {
2✔
1689

2✔
1690
        client := &SingleInvoiceSubscription{
2✔
1691
                Updates: make(chan *Invoice),
2✔
1692
                invoiceSubscriptionKit: invoiceSubscriptionKit{
2✔
1693
                        quit:             i.quit,
2✔
1694
                        ntfnQueue:        queue.NewConcurrentQueue(20),
2✔
1695
                        cancelChan:       make(chan struct{}),
2✔
1696
                        backlogDelivered: make(chan struct{}),
2✔
1697
                },
2✔
1698
                invoiceRef: InvoiceRefByHash(hash),
2✔
1699
        }
2✔
1700
        client.ntfnQueue.Start()
2✔
1701

2✔
1702
        // This notifies other goroutines that the backlog phase is done.
2✔
1703
        defer close(client.backlogDelivered)
2✔
1704

2✔
1705
        // Always increment by 1 first, and our client ID will start with 1,
2✔
1706
        // not 0.
2✔
1707
        client.id = atomic.AddUint32(&i.nextClientID, 1)
2✔
1708

2✔
1709
        // Before we register this new invoice subscription, we'll launch a new
2✔
1710
        // goroutine that will proxy all notifications appended to the end of
2✔
1711
        // the concurrent queue to the two client-side channels the caller will
2✔
1712
        // feed off of.
2✔
1713
        i.wg.Add(1)
2✔
1714
        go func() {
4✔
1715
                defer i.wg.Done()
2✔
1716
                defer i.deleteClient(client.id)
2✔
1717

2✔
1718
                for {
4✔
1719
                        select {
2✔
1720
                        // A new invoice event has been sent by the
1721
                        // invoiceRegistry. We will dispatch the event to the
1722
                        // client.
1723
                        case ntfn := <-client.ntfnQueue.ChanOut():
2✔
1724
                                invoiceEvent := ntfn.(*invoiceEvent)
2✔
1725

2✔
1726
                                select {
2✔
1727
                                case client.Updates <- invoiceEvent.invoice:
2✔
1728

1729
                                case <-client.cancelChan:
×
1730
                                        return
×
1731

1732
                                case <-i.quit:
×
1733
                                        return
×
1734
                                }
1735

1736
                        case <-client.cancelChan:
2✔
1737
                                return
2✔
1738

UNCOV
1739
                        case <-i.quit:
×
UNCOV
1740
                                return
×
1741
                        }
1742
                }
1743
        }()
1744

1745
        i.notificationClientMux.Lock()
2✔
1746
        i.singleNotificationClients[client.id] = client
2✔
1747
        i.notificationClientMux.Unlock()
2✔
1748

2✔
1749
        err := i.deliverSingleBacklogEvents(ctx, client)
2✔
1750
        if err != nil {
2✔
1751
                return nil, err
×
1752
        }
×
1753

1754
        log.Infof("New single invoice subscription client: id=%v, ref=%v",
2✔
1755
                client.id, client.invoiceRef)
2✔
1756

2✔
1757
        return client, nil
2✔
1758
}
1759

1760
// notifyHodlSubscribers sends out the htlc resolution to all current
1761
// subscribers.
1762
func (i *InvoiceRegistry) notifyHodlSubscribers(htlcResolution HtlcResolution) {
2✔
1763
        i.hodlSubscriptionsMux.Lock()
2✔
1764
        defer i.hodlSubscriptionsMux.Unlock()
2✔
1765

2✔
1766
        subscribers, ok := i.hodlSubscriptions[htlcResolution.CircuitKey()]
2✔
1767
        if !ok {
4✔
1768
                return
2✔
1769
        }
2✔
1770

1771
        // Notify all interested subscribers and remove subscription from both
1772
        // maps. The subscription can be removed as there only ever will be a
1773
        // single resolution for each hash.
1774
        for subscriber := range subscribers {
4✔
1775
                select {
2✔
1776
                case subscriber <- htlcResolution:
2✔
1777
                case <-i.quit:
×
1778
                        return
×
1779
                }
1780

1781
                delete(
2✔
1782
                        i.hodlReverseSubscriptions[subscriber],
2✔
1783
                        htlcResolution.CircuitKey(),
2✔
1784
                )
2✔
1785
        }
1786

1787
        delete(i.hodlSubscriptions, htlcResolution.CircuitKey())
2✔
1788
}
1789

1790
// hodlSubscribe adds a new invoice subscription.
1791
func (i *InvoiceRegistry) hodlSubscribe(subscriber chan<- interface{},
1792
        circuitKey CircuitKey) {
2✔
1793

2✔
1794
        i.hodlSubscriptionsMux.Lock()
2✔
1795
        defer i.hodlSubscriptionsMux.Unlock()
2✔
1796

2✔
1797
        log.Debugf("Hodl subscribe for %v", circuitKey)
2✔
1798

2✔
1799
        subscriptions, ok := i.hodlSubscriptions[circuitKey]
2✔
1800
        if !ok {
4✔
1801
                subscriptions = make(map[chan<- interface{}]struct{})
2✔
1802
                i.hodlSubscriptions[circuitKey] = subscriptions
2✔
1803
        }
2✔
1804
        subscriptions[subscriber] = struct{}{}
2✔
1805

2✔
1806
        reverseSubscriptions, ok := i.hodlReverseSubscriptions[subscriber]
2✔
1807
        if !ok {
4✔
1808
                reverseSubscriptions = make(map[CircuitKey]struct{})
2✔
1809
                i.hodlReverseSubscriptions[subscriber] = reverseSubscriptions
2✔
1810
        }
2✔
1811
        reverseSubscriptions[circuitKey] = struct{}{}
2✔
1812
}
1813

1814
// HodlUnsubscribeAll cancels the subscription.
1815
func (i *InvoiceRegistry) HodlUnsubscribeAll(subscriber chan<- interface{}) {
2✔
1816
        i.hodlSubscriptionsMux.Lock()
2✔
1817
        defer i.hodlSubscriptionsMux.Unlock()
2✔
1818

2✔
1819
        hashes := i.hodlReverseSubscriptions[subscriber]
2✔
1820
        for hash := range hashes {
4✔
1821
                delete(i.hodlSubscriptions[hash], subscriber)
2✔
1822
        }
2✔
1823

1824
        delete(i.hodlReverseSubscriptions, subscriber)
2✔
1825
}
1826

1827
// copySingleClients copies i.SingleInvoiceSubscription inside a lock. This is
1828
// useful when we need to iterate the map to send notifications.
1829
func (i *InvoiceRegistry) copySingleClients() map[uint32]*SingleInvoiceSubscription { //nolint:lll
2✔
1830
        i.notificationClientMux.RLock()
2✔
1831
        defer i.notificationClientMux.RUnlock()
2✔
1832

2✔
1833
        clients := make(map[uint32]*SingleInvoiceSubscription)
2✔
1834
        for k, v := range i.singleNotificationClients {
4✔
1835
                clients[k] = v
2✔
1836
        }
2✔
1837
        return clients
2✔
1838
}
1839

1840
// copyClients copies i.notificationClients inside a lock. This is useful when
1841
// we need to iterate the map to send notifications.
1842
func (i *InvoiceRegistry) copyClients() map[uint32]*InvoiceSubscription {
2✔
1843
        i.notificationClientMux.RLock()
2✔
1844
        defer i.notificationClientMux.RUnlock()
2✔
1845

2✔
1846
        clients := make(map[uint32]*InvoiceSubscription)
2✔
1847
        for k, v := range i.notificationClients {
4✔
1848
                clients[k] = v
2✔
1849
        }
2✔
1850
        return clients
2✔
1851
}
1852

1853
// deleteClient removes a client by its ID inside a lock. Noop if the client is
1854
// not found.
1855
func (i *InvoiceRegistry) deleteClient(clientID uint32) {
2✔
1856
        i.notificationClientMux.Lock()
2✔
1857
        defer i.notificationClientMux.Unlock()
2✔
1858

2✔
1859
        log.Infof("Cancelling invoice subscription for client=%v", clientID)
2✔
1860
        delete(i.notificationClients, clientID)
2✔
1861
        delete(i.singleNotificationClients, clientID)
2✔
1862
}
2✔
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