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

lightningnetwork / lnd / 11136034567

02 Oct 2024 01:06AM UTC coverage: 58.817% (+0.003%) from 58.814%
11136034567

push

github

web-flow
Merge pull request #8644 from Roasbeef/remove-sql-mutex-part-deux

kvdb/postgres: remove global application level lock

130416 of 221731 relevant lines covered (58.82%)

28306.61 hits per line

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

85.11
/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 {
10✔
101
        return r.releaseTime.Before(other.(*htlcReleaseEvent).releaseTime)
10✔
102
}
10✔
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 {
638✔
166

638✔
167
        notificationClients := make(map[uint32]*InvoiceSubscription)
638✔
168
        singleNotificationClients := make(map[uint32]*SingleInvoiceSubscription)
638✔
169
        return &InvoiceRegistry{
638✔
170
                idb:                       idb,
638✔
171
                notificationClients:       notificationClients,
638✔
172
                singleNotificationClients: singleNotificationClients,
638✔
173
                invoiceEvents:             make(chan *invoiceEvent, 100),
638✔
174
                hodlSubscriptions: make(
638✔
175
                        map[CircuitKey]map[chan<- interface{}]struct{},
638✔
176
                ),
638✔
177
                hodlReverseSubscriptions: make(
638✔
178
                        map[chan<- interface{}]map[CircuitKey]struct{},
638✔
179
                ),
638✔
180
                cfg:                 cfg,
638✔
181
                htlcAutoReleaseChan: make(chan *htlcReleaseEvent),
638✔
182
                expiryWatcher:       expiryWatcher,
638✔
183
                quit:                make(chan struct{}),
638✔
184
        }
638✔
185
}
638✔
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 {
638✔
191
        pendingInvoices, err := i.idb.FetchPendingInvoices(ctx)
638✔
192
        if err != nil {
638✔
193
                return err
×
194
        }
×
195

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

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

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

218
        return nil
638✔
219
}
220

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

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

638✔
227
        if i.started.Swap(true) {
638✔
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(
638✔
233
                func(hash lntypes.Hash, force bool) error {
715✔
234
                        return i.cancelInvoiceImpl(
77✔
235
                                context.Background(), hash, force,
77✔
236
                        )
77✔
237
                })
77✔
238
        if err != nil {
638✔
239
                return err
×
240
        }
×
241

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

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

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

638✔
254
        return err
638✔
255
}
256

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

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

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

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

276
        close(i.quit)
379✔
277

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

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

379✔
282
        return err
379✔
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 {
655✔
297
        now := i.cfg.Clock.Now()
655✔
298
        return i.cfg.Clock.TickAfter(t.Sub(now))
655✔
299
}
655✔
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() {
638✔
305
        defer i.wg.Done()
638✔
306

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

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

319
                select {
3,668✔
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,692✔
323
                        // For backwards compatibility, do not notify all
2,692✔
324
                        // invoice subscribers of cancel and accept events.
2,692✔
325
                        state := event.invoice.State
2,692✔
326
                        if state != ContractCanceled &&
2,692✔
327
                                state != ContractAccepted {
4,795✔
328

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

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

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

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

356
                case <-i.quit:
379✔
357
                        return
379✔
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,692✔
365
        // Dispatch to single invoice subscribers.
2,692✔
366
        clients := i.copySingleClients()
2,692✔
367
        for _, client := range clients {
2,732✔
368
                payHash := client.invoiceRef.PayHash()
40✔
369

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

374
                select {
40✔
375
                case <-client.backlogDelivered:
40✔
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)
40✔
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,103✔
390
        invoice := event.invoice
2,103✔
391

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

70✔
399
                // TODO(joostjager): Refactor switches.
70✔
400
                state := event.invoice.State
70✔
401
                switch {
70✔
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:
11✔
421
                        log.Warnf("client=%v for invoice "+
11✔
422
                                "notifications missed an update, "+
11✔
423
                                "add_index=%v, new add event index=%v",
11✔
424
                                clientID, client.addIndex,
11✔
425
                                invoice.AddIndex)
11✔
426

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

436
                select {
70✔
437
                case <-client.backlogDelivered:
70✔
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{
70✔
445
                        invoice: invoice,
70✔
446
                        setID:   event.setID,
70✔
447
                })
70✔
448
                if err != nil {
70✔
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
70✔
458
                switch {
70✔
459
                case invState == ContractSettled:
22✔
460
                        client.settleIndex = invoice.SettleIndex
22✔
461

462
                case invState == ContractOpen && event.setID == nil:
46✔
463
                        client.addIndex = invoice.AddIndex
46✔
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:
10✔
471
                        setID := *event.setID
10✔
472
                        client.settleIndex = invoice.AMPState[setID].SettleIndex
10✔
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 {
49✔
485

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

491
        settleEvents, err := i.idb.InvoicesSettledSince(ctx, client.settleIndex)
49✔
492
        if err != nil {
49✔
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 {
53✔
500
                // We re-bind the loop variable to ensure we don't hold onto
4✔
501
                // the loop reference causing is to point to the same item.
4✔
502
                addEvent := addEvent
4✔
503

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

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

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

527
        return nil
49✔
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 {
22✔
537

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

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

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

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

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

4✔
567
        return nil
4✔
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) {
1,156✔
580

1,156✔
581
        i.Lock()
1,156✔
582

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

1,156✔
586
        addIndex, err := i.idb.AddInvoice(ctx, invoice, paymentHash)
1,156✔
587
        if err != nil {
1,175✔
588
                i.Unlock()
19✔
589
                return 0, err
19✔
590
        }
19✔
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)
1,141✔
595
        i.Unlock()
1,141✔
596

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

605
        return addIndex, nil
1,141✔
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) {
399✔
614

399✔
615
        // We'll check the database to see if there's an existing matching
399✔
616
        // invoice.
399✔
617
        ref := InvoiceRefByHash(rHash)
399✔
618
        return i.idb.LookupInvoice(ctx, ref)
399✔
619
}
399✔
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) {
4✔
625

4✔
626
        return i.idb.LookupInvoice(ctx, ref)
4✔
627
}
4✔
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 {
334✔
633

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

334✔
641
        select {
334✔
642
        case i.htlcAutoReleaseChan <- event:
334✔
643
                return nil
334✔
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 {
15✔
655

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

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

665
                // Lookup the current status of the htlc in the database.
666
                var (
6✔
667
                        htlcState HtlcState
6✔
668
                        setID     *SetID
6✔
669
                )
6✔
670
                htlc, ok := invoice.Htlcs[key]
6✔
671
                if !ok {
6✔
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
                        }
×
692
                } else {
6✔
693
                        htlcState = htlc.State
6✔
694
                }
6✔
695

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

×
702
                        return nil, nil
×
703
                }
×
704

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

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

6✔
714
                return &InvoiceUpdateDesc{
6✔
715
                        UpdateType:  CancelHTLCsUpdate,
6✔
716
                        CancelHtlcs: canceledHtlcs,
6✔
717
                        SetID:       setID,
6✔
718
                }, nil
6✔
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())
15✔
725
        var updated bool
15✔
726
        invoice, err := i.idb.UpdateInvoice(
15✔
727
                context.Background(), invoiceRef, setID,
15✔
728
                func(invoice *Invoice) (
15✔
729
                        *InvoiceUpdateDesc, error) {
30✔
730

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

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

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

6✔
758
                i.notifyHodlSubscribers(resolution)
6✔
759
        }
6✔
760
        return nil
6✔
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 {
22✔
766
        // Retrieve keysend record if present.
22✔
767
        preimageSlice, ok := ctx.customRecords[record.KeySendType]
22✔
768
        if !ok {
26✔
769
                return nil
4✔
770
        }
4✔
771

772
        // Cancel htlc is preimage is invalid.
773
        preimage, err := lntypes.MakePreimage(preimageSlice)
22✔
774
        if err != nil {
25✔
775
                return err
3✔
776
        }
3✔
777
        if preimage.Hash() != ctx.hash {
19✔
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 {
19✔
784
                return errors.New("no mpp keysend supported")
×
785
        }
×
786

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

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

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

19✔
800
        // Pre-check expiry here to prevent inserting an invoice that will not
19✔
801
        // be settled.
19✔
802
        if ctx.expiry < uint32(ctx.currentHeight+finalCltvDelta) {
19✔
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
19✔
814

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

19✔
827
        if i.cfg.KeysendHoldTime != 0 {
25✔
828
                invoice.HodlInvoice = true
6✔
829
                invoice.Terms.Expiry = i.cfg.KeysendHoldTime
6✔
830
        }
6✔
831

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

839
        return nil
19✔
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 {
31✔
845
        // AMP payments MUST also include an MPP record.
31✔
846
        if ctx.mpp == nil {
34✔
847
                return errors.New("no MPP record for AMP")
3✔
848
        }
3✔
849

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

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

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

28✔
867
        // Pre-check expiry here to prevent inserting an invoice that will not
28✔
868
        // be settled.
28✔
869
        if ctx.expiry < uint32(ctx.currentHeight+finalCltvDelta) {
28✔
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()
28✔
876

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

28✔
889
        // Insert invoice into database. Ignore duplicates payment hashes and
28✔
890
        // payment addrs, this may be a replay or a different HTLC for the AMP
28✔
891
        // invoice.
28✔
892
        _, err := i.AddInvoice(context.Background(), invoice, ctx.hash)
28✔
893
        isDuplicatedInvoice := errors.Is(err, ErrDuplicateInvoice)
28✔
894
        isDuplicatedPayAddr := errors.Is(err, ErrDuplicatePayAddr)
28✔
895
        switch {
28✔
896
        case isDuplicatedInvoice || isDuplicatedPayAddr:
16✔
897
                return nil
16✔
898
        default:
16✔
899
                return err
16✔
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) {
1,383✔
923

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

1,383✔
942
        switch {
1,383✔
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:
31✔
947
                err := i.processAMP(ctx)
31✔
948
                if err != nil {
34✔
949
                        ctx.log(fmt.Sprintf("amp error: %v", err))
3✔
950

3✔
951
                        return NewFailResolution(
3✔
952
                                circuitKey, currentHeight, ResultAmpError,
3✔
953
                        ), nil
3✔
954
                }
3✔
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:
22✔
961
                err := i.processKeySend(ctx)
22✔
962
                if err != nil {
25✔
963
                        ctx.log(fmt.Sprintf("keysend error: %v", err))
3✔
964

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

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

981
        if invoiceToExpire != nil {
1,896✔
982
                i.expiryWatcher.AddInvoices(invoiceToExpire)
519✔
983
        }
519✔
984

985
        switch r := resolution.(type) {
1,377✔
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:
856✔
990
                if r.autoRelease {
1,190✔
991
                        var invRef InvoiceRef
334✔
992
                        if ctx.amp != nil {
350✔
993
                                invRef = InvoiceRefBySetID(*ctx.setID())
16✔
994
                        } else {
338✔
995
                                invRef = ctx.invoiceRef()
322✔
996
                        }
322✔
997

998
                        err := i.startHtlcTimer(
334✔
999
                                invRef, circuitKey, r.acceptTime,
334✔
1000
                        )
334✔
1001
                        if err != nil {
334✔
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
856✔
1010

1011
        // A direct resolution was received for this htlc.
1012
        case HtlcResolution:
525✔
1013
                return r, nil
525✔
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) {
1,377✔
1027

1,377✔
1028
        invoiceRef := ctx.invoiceRef()
1,377✔
1029
        setID := (*SetID)(ctx.setID())
1,377✔
1030

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

26✔
1040
                // If the invoice was not found, return a failure resolution
26✔
1041
                // with an invoice not found result.
26✔
1042
                return NewFailResolution(
26✔
1043
                        ctx.circuitKey, ctx.currentHeight,
26✔
1044
                        ResultInvoiceNotFound,
26✔
1045
                ), nil, nil
26✔
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{
1,355✔
1056
                WireCustomRecords:  ctx.wireCustomRecords,
1,355✔
1057
                ExitHtlcCircuitKey: ctx.circuitKey,
1,355✔
1058
                ExitHtlcAmt:        ctx.amtPaid,
1,355✔
1059
                ExitHtlcExpiry:     ctx.expiry,
1,355✔
1060
                CurrentHeight:      uint32(ctx.currentHeight),
1,355✔
1061
                Invoice:            existingInvoice,
1,355✔
1062
        }, func(resp HtlcModifyResponse) {
1,359✔
1063
                log.Debugf("Received invoice HTLC interceptor response: %v",
4✔
1064
                        resp)
4✔
1065

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

4✔
1075
                return nil, nil, err
4✔
1076
        }
4✔
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 (
1,355✔
1081
                resolution        HtlcResolution
1,355✔
1082
                updateSubscribers bool
1,355✔
1083
        )
1,355✔
1084
        callback := func(inv *Invoice) (*InvoiceUpdateDesc, error) {
2,710✔
1085
                updateDesc, res, err := updateInvoice(ctx, inv)
1,355✔
1086
                if err != nil {
1,355✔
1087
                        return nil, err
×
1088
                }
×
1089

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

1,355✔
1094
                // Assign resolution to outer scope variable.
1,355✔
1095
                resolution = res
1,355✔
1096

1,355✔
1097
                return updateDesc, nil
1,355✔
1098
        }
1099

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

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

1112
        switch {
1,355✔
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:
1,355✔
1128

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

1134
        var invoiceToExpire invoiceExpiry
1,355✔
1135

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

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

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

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

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

6✔
1171
                        i.notifyHodlSubscribers(htlcFailResolution)
6✔
1172
                }
6✔
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:
477✔
1177
                ctx.log(fmt.Sprintf("settle resolution result "+
477✔
1178
                        "outcome: %v, at accept height: %v",
477✔
1179
                        res.Outcome, res.AcceptHeight))
477✔
1180

477✔
1181
                // Also settle any previously accepted htlcs. If a htlc is
477✔
1182
                // marked as settled, we should follow now and settle the htlc
477✔
1183
                // with our peer.
477✔
1184
                setID := ctx.setID()
477✔
1185
                settledHtlcSet := invoice.HTLCSet(setID, HtlcStateSettled)
477✔
1186
                for key, htlc := range settledHtlcSet {
1,266✔
1187
                        preimage := res.Preimage
789✔
1188
                        if htlc.AMP != nil && htlc.AMP.Preimage != nil {
805✔
1189
                                preimage = *htlc.AMP.Preimage
16✔
1190
                        }
16✔
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(
789✔
1198
                                preimage, key,
789✔
1199
                                int32(htlc.AcceptHeight), res.Outcome,
789✔
1200
                        )
789✔
1201

789✔
1202
                        // Notify subscribers that the htlc should be settled
789✔
1203
                        // with our peer.
789✔
1204
                        i.notifyHodlSubscribers(htlcSettleResolution)
789✔
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(
477✔
1215
                        setID, HtlcStateCanceled,
477✔
1216
                )
477✔
1217
                for key, htlc := range canceledHtlcSet {
477✔
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:
856✔
1229
                invoiceHtlc, ok := invoice.Htlcs[ctx.circuitKey]
856✔
1230
                if !ok {
856✔
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)
856✔
1241

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

856✔
1246
                // Auto-release the htlc if the invoice is still open. It can
856✔
1247
                // only happen for mpp payments that there are htlcs in state
856✔
1248
                // Accepted while the invoice is Open.
856✔
1249
                if invoice.State == ContractOpen {
1,190✔
1250
                        res.acceptTime = invoiceHtlc.AcceptTime
334✔
1251
                        res.autoRelease = true
334✔
1252
                }
334✔
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 {
1,375✔
1260
                        invoiceToExpire = makeInvoiceExpiry(ctx.hash, invoice)
519✔
1261
                }
519✔
1262

1263
                i.hodlSubscribe(hodlChan, ctx.circuitKey)
856✔
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 {
2,344✔
1273
                // We'll add a setID onto the notification, but only if this is
989✔
1274
                // an AMP invoice being settled.
989✔
1275
                var setID *[32]byte
989✔
1276
                if _, ok := resolution.(*HtlcSettleResolution); ok {
1,457✔
1277
                        setID = ctx.setID()
468✔
1278
                }
468✔
1279

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

1283
        return resolution, invoiceToExpire, nil
1,355✔
1284
}
1285

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

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

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

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

1301
                case ContractSettled:
3✔
1302
                        return nil, ErrInvoiceAlreadySettled
3✔
1303
                }
1304

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

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

3✔
1321
                return err
3✔
1322
        }
3✔
1323

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

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

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

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

503✔
1346
        return nil
503✔
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 {
33✔
1353

33✔
1354
        return i.cancelInvoiceImpl(ctx, payHash, true)
33✔
1355
}
33✔
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 {
97✔
1362
        if state != ContractAccepted {
166✔
1363
                return true
69✔
1364
        }
69✔
1365

1366
        // If the invoice is accepted, we should only cancel if we want to
1367
        // force cancellation of accepted invoices.
1368
        return cancelAccepted
32✔
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 {
106✔
1377

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

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

106✔
1384
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
203✔
1385
                if !shouldCancel(invoice.State, cancelAccepted) {
109✔
1386
                        return nil, nil
12✔
1387
                }
12✔
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{
85✔
1393
                        UpdateType: CancelInvoiceUpdate,
85✔
1394
                        State: &InvoiceStateUpdateDesc{
85✔
1395
                                NewState: ContractCanceled,
85✔
1396
                        },
85✔
1397
                }, nil
85✔
1398
        }
1399

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

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

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

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

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

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

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

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

1464
        return nil
72✔
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,693✔
1471

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

2,693✔
1478
        select {
2,693✔
1479
        case i.invoiceEvents <- event:
2,693✔
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.
1550
func (s *SingleInvoiceSubscription) PayHash() *lntypes.Hash {
18✔
1551
        return s.invoiceRef.PayHash()
18✔
1552
}
18✔
1553

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

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

1565
func (i *invoiceSubscriptionKit) notify(event *invoiceEvent) error {
106✔
1566
        select {
106✔
1567
        case i.ntfnQueue.ChanIn() <- event:
106✔
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
106✔
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) {
49✔
1587

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

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

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

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

49✔
1618
                for {
164✔
1619
                        select {
115✔
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():
70✔
1625
                                invoiceEvent := ntfn.(*invoiceEvent)
70✔
1626

70✔
1627
                                var targetChan chan *Invoice
70✔
1628
                                state := invoiceEvent.invoice.State
70✔
1629
                                switch {
70✔
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:
10✔
1635
                                        fallthrough
10✔
1636

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

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

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

×
1647
                                        continue
×
1648
                                }
1649

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

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

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

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

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

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

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

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

49✔
1682
        return client, nil
49✔
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) {
22✔
1689

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

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

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

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

22✔
1718
                for {
80✔
1719
                        select {
58✔
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():
40✔
1724
                                invoiceEvent := ntfn.(*invoiceEvent)
40✔
1725

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

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

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

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

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

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

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

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

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

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

1,328✔
1766
        subscribers, ok := i.hodlSubscriptions[htlcResolution.CircuitKey()]
1,328✔
1767
        if !ok {
1,811✔
1768
                return
483✔
1769
        }
483✔
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 {
1,698✔
1775
                select {
849✔
1776
                case subscriber <- htlcResolution:
849✔
1777
                case <-i.quit:
×
1778
                        return
×
1779
                }
1780

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

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

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

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

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

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

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

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

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

1824
        delete(i.hodlReverseSubscriptions, subscriber)
204✔
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,692✔
1830
        i.notificationClientMux.RLock()
2,692✔
1831
        defer i.notificationClientMux.RUnlock()
2,692✔
1832

2,692✔
1833
        clients := make(map[uint32]*SingleInvoiceSubscription)
2,692✔
1834
        for k, v := range i.singleNotificationClients {
2,732✔
1835
                clients[k] = v
40✔
1836
        }
40✔
1837
        return clients
2,692✔
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,103✔
1843
        i.notificationClientMux.RLock()
2,103✔
1844
        defer i.notificationClientMux.RUnlock()
2,103✔
1845

2,103✔
1846
        clients := make(map[uint32]*InvoiceSubscription)
2,103✔
1847
        for k, v := range i.notificationClients {
2,173✔
1848
                clients[k] = v
70✔
1849
        }
70✔
1850
        return clients
2,103✔
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) {
67✔
1856
        i.notificationClientMux.Lock()
67✔
1857
        defer i.notificationClientMux.Unlock()
67✔
1858

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