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

lightningnetwork / lnd / 13035292482

29 Jan 2025 03:59PM UTC coverage: 49.3% (-9.5%) from 58.777%
13035292482

Pull #9456

github

mohamedawnallah
docs: update release-notes-0.19.0.md

In this commit, we warn users about the removal
of RPCs `SendToRoute`, `SendToRouteSync`, `SendPayment`,
and `SendPaymentSync` in the next release 0.20.
Pull Request #9456: lnrpc+docs: deprecate warning `SendToRoute`, `SendToRouteSync`, `SendPayment`, and `SendPaymentSync` in Release 0.19

100634 of 204126 relevant lines covered (49.3%)

1.54 hits per line

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

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

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

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

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

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

218
        return nil
3✔
219
}
220

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

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

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

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

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

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

3✔
254
        return err
3✔
255
}
256

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

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

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

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

276
        close(i.quit)
3✔
277

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
567
        return nil
3✔
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) {
3✔
580

3✔
581
        i.Lock()
3✔
582

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

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

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

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

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

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

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

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

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

×
662
                        return nil, nil
×
663
                }
×
664

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

696
                // Cancellation is only possible if the htlc wasn't already
697
                // resolved.
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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
827
        if i.cfg.KeysendHoldTime != 0 {
3✔
828
                invoice.HodlInvoice = true
×
829
                invoice.Terms.Expiry = i.cfg.KeysendHoldTime
×
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)
3✔
835
        if err != nil && !errors.Is(err, ErrDuplicateInvoice) {
3✔
836
                return err
×
837
        }
×
838

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

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

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

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

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

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

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

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

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

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

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

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

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

985
        switch r := resolution.(type) {
3✔
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:
3✔
990
                if r.autoRelease {
6✔
991
                        var invRef InvoiceRef
3✔
992
                        if ctx.amp != nil {
6✔
993
                                invRef = InvoiceRefBySetID(*ctx.setID())
3✔
994
                        } else {
6✔
995
                                invRef = ctx.invoiceRef()
3✔
996
                        }
3✔
997

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

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

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

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

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

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

1052
        var cancelSet bool
3✔
1053

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

3✔
1068
                if resp.AmountPaid != 0 {
6✔
1069
                        ctx.amtPaid = resp.AmountPaid
3✔
1070
                }
3✔
1071

1072
                cancelSet = resp.CancelSet
3✔
1073
        })
1074
        if err != nil {
6✔
1075
                err := fmt.Errorf("error during invoice HTLC interception: %w",
3✔
1076
                        err)
3✔
1077
                ctx.log(err.Error())
3✔
1078

3✔
1079
                return nil, nil, err
3✔
1080
        }
3✔
1081

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

1094
                // Only send an update if the invoice state was changed.
1095
                updateSubscribers = updateDesc != nil &&
3✔
1096
                        updateDesc.State != nil
3✔
1097

3✔
1098
                // Assign resolution to outer scope variable.
3✔
1099
                if cancelSet {
3✔
1100
                        // If a cancel signal was set for the htlc set, we set
×
1101
                        // the resolution as a failure with an underpayment
×
1102
                        // indication. Something was wrong with this htlc, so
×
1103
                        // we probably can't settle the invoice at all.
×
1104
                        resolution = NewFailResolution(
×
1105
                                ctx.circuitKey, ctx.currentHeight,
×
1106
                                ResultAmountTooLow,
×
1107
                        )
×
1108
                } else {
3✔
1109
                        resolution = res
3✔
1110
                }
3✔
1111

1112
                return updateDesc, nil
3✔
1113
        }
1114

1115
        invoice, err := i.idb.UpdateInvoice(
3✔
1116
                context.Background(), invoiceRef, setID, callback,
3✔
1117
        )
3✔
1118

3✔
1119
        var duplicateSetIDErr ErrDuplicateSetID
3✔
1120
        if errors.As(err, &duplicateSetIDErr) {
3✔
1121
                return NewFailResolution(
×
1122
                        ctx.circuitKey, ctx.currentHeight,
×
1123
                        ResultInvoiceNotFound,
×
1124
                ), nil, nil
×
1125
        }
×
1126

1127
        switch {
3✔
1128
        case errors.Is(err, ErrInvoiceNotFound):
×
1129
                // If the invoice was not found, return a failure resolution
×
1130
                // with an invoice not found result.
×
1131
                return NewFailResolution(
×
1132
                        ctx.circuitKey, ctx.currentHeight,
×
1133
                        ResultInvoiceNotFound,
×
1134
                ), nil, nil
×
1135

1136
        case errors.Is(err, ErrInvRefEquivocation):
×
1137
                return NewFailResolution(
×
1138
                        ctx.circuitKey, ctx.currentHeight,
×
1139
                        ResultInvoiceNotFound,
×
1140
                ), nil, nil
×
1141

1142
        case err == nil:
3✔
1143

1144
        default:
×
1145
                ctx.log(err.Error())
×
1146
                return nil, nil, err
×
1147
        }
1148

1149
        var invoiceToExpire invoiceExpiry
3✔
1150

3✔
1151
        log.Tracef("Settlement resolution: %T %v", resolution, resolution)
3✔
1152

3✔
1153
        switch res := resolution.(type) {
3✔
1154
        case *HtlcFailResolution:
3✔
1155
                // Inspect latest htlc state on the invoice. If it is found,
3✔
1156
                // we will update the accept height as it was recorded in the
3✔
1157
                // invoice database (which occurs in the case where the htlc
3✔
1158
                // reached the database in a previous call). If the htlc was
3✔
1159
                // not found on the invoice, it was immediately failed so we
3✔
1160
                // send the failure resolution as is, which has the current
3✔
1161
                // height set as the accept height.
3✔
1162
                invoiceHtlc, ok := invoice.Htlcs[ctx.circuitKey]
3✔
1163
                if ok {
6✔
1164
                        res.AcceptHeight = int32(invoiceHtlc.AcceptHeight)
3✔
1165
                }
3✔
1166

1167
                ctx.log(fmt.Sprintf("failure resolution result "+
3✔
1168
                        "outcome: %v, at accept height: %v",
3✔
1169
                        res.Outcome, res.AcceptHeight))
3✔
1170

3✔
1171
                // Some failures apply to the entire HTLC set. Break here if
3✔
1172
                // this isn't one of them.
3✔
1173
                if !res.Outcome.IsSetFailure() {
6✔
1174
                        break
3✔
1175
                }
1176

1177
                // Also cancel any HTLCs in the HTLC set that are also in the
1178
                // canceled state with the same failure result.
1179
                setID := ctx.setID()
×
1180
                canceledHtlcSet := invoice.HTLCSet(setID, HtlcStateCanceled)
×
1181
                for key, htlc := range canceledHtlcSet {
×
1182
                        htlcFailResolution := NewFailResolution(
×
1183
                                key, int32(htlc.AcceptHeight), res.Outcome,
×
1184
                        )
×
1185

×
1186
                        i.notifyHodlSubscribers(htlcFailResolution)
×
1187
                }
×
1188

1189
        // If the htlc was settled, we will settle any previously accepted
1190
        // htlcs and notify our peer to settle them.
1191
        case *HtlcSettleResolution:
3✔
1192
                ctx.log(fmt.Sprintf("settle resolution result "+
3✔
1193
                        "outcome: %v, at accept height: %v",
3✔
1194
                        res.Outcome, res.AcceptHeight))
3✔
1195

3✔
1196
                // Also settle any previously accepted htlcs. If a htlc is
3✔
1197
                // marked as settled, we should follow now and settle the htlc
3✔
1198
                // with our peer.
3✔
1199
                setID := ctx.setID()
3✔
1200
                settledHtlcSet := invoice.HTLCSet(setID, HtlcStateSettled)
3✔
1201
                for key, htlc := range settledHtlcSet {
6✔
1202
                        preimage := res.Preimage
3✔
1203
                        if htlc.AMP != nil && htlc.AMP.Preimage != nil {
6✔
1204
                                preimage = *htlc.AMP.Preimage
3✔
1205
                        }
3✔
1206

1207
                        // Notify subscribers that the htlcs should be settled
1208
                        // with our peer. Note that the outcome of the
1209
                        // resolution is set based on the outcome of the single
1210
                        // htlc that we just settled, so may not be accurate
1211
                        // for all htlcs.
1212
                        htlcSettleResolution := NewSettleResolution(
3✔
1213
                                preimage, key,
3✔
1214
                                int32(htlc.AcceptHeight), res.Outcome,
3✔
1215
                        )
3✔
1216

3✔
1217
                        // Notify subscribers that the htlc should be settled
3✔
1218
                        // with our peer.
3✔
1219
                        i.notifyHodlSubscribers(htlcSettleResolution)
3✔
1220
                }
1221

1222
                // If concurrent payments were attempted to this invoice before
1223
                // the current one was ultimately settled, cancel back any of
1224
                // the HTLCs immediately. As a result of the settle, the HTLCs
1225
                // in other HTLC sets are automatically converted to a canceled
1226
                // state when updating the invoice.
1227
                //
1228
                // TODO(roasbeef): can remove now??
1229
                canceledHtlcSet := invoice.HTLCSetCompliment(
3✔
1230
                        setID, HtlcStateCanceled,
3✔
1231
                )
3✔
1232
                for key, htlc := range canceledHtlcSet {
3✔
1233
                        htlcFailResolution := NewFailResolution(
×
1234
                                key, int32(htlc.AcceptHeight),
×
1235
                                ResultInvoiceAlreadySettled,
×
1236
                        )
×
1237

×
1238
                        i.notifyHodlSubscribers(htlcFailResolution)
×
1239
                }
×
1240

1241
        // If we accepted the htlc, subscribe to the hodl invoice and return
1242
        // an accept resolution with the htlc's accept time on it.
1243
        case *htlcAcceptResolution:
3✔
1244
                invoiceHtlc, ok := invoice.Htlcs[ctx.circuitKey]
3✔
1245
                if !ok {
3✔
1246
                        return nil, nil, fmt.Errorf("accepted htlc: %v not"+
×
1247
                                " present on invoice: %x", ctx.circuitKey,
×
1248
                                ctx.hash[:])
×
1249
                }
×
1250

1251
                // Determine accepted height of this htlc. If the htlc reached
1252
                // the invoice database (possibly in a previous call to the
1253
                // invoice registry), we'll take the original accepted height
1254
                // as it was recorded in the database.
1255
                acceptHeight := int32(invoiceHtlc.AcceptHeight)
3✔
1256

3✔
1257
                ctx.log(fmt.Sprintf("accept resolution result "+
3✔
1258
                        "outcome: %v, at accept height: %v",
3✔
1259
                        res.outcome, acceptHeight))
3✔
1260

3✔
1261
                // Auto-release the htlc if the invoice is still open. It can
3✔
1262
                // only happen for mpp payments that there are htlcs in state
3✔
1263
                // Accepted while the invoice is Open.
3✔
1264
                if invoice.State == ContractOpen {
6✔
1265
                        res.acceptTime = invoiceHtlc.AcceptTime
3✔
1266
                        res.autoRelease = true
3✔
1267
                }
3✔
1268

1269
                // If we have fully accepted the set of htlcs for this invoice,
1270
                // we can now add it to our invoice expiry watcher. We do not
1271
                // add invoices before they are fully accepted, because it is
1272
                // possible that we MppTimeout the htlcs, and then our relevant
1273
                // expiry height could change.
1274
                if res.outcome == resultAccepted {
6✔
1275
                        invoiceToExpire = makeInvoiceExpiry(ctx.hash, invoice)
3✔
1276
                }
3✔
1277

1278
                // Subscribe to the resolution if the caller specified a
1279
                // notification channel.
1280
                if hodlChan != nil {
6✔
1281
                        i.hodlSubscribe(hodlChan, ctx.circuitKey)
3✔
1282
                }
3✔
1283

1284
        default:
×
1285
                panic("unknown action")
×
1286
        }
1287

1288
        // Now that the links have been notified of any state changes to their
1289
        // HTLCs, we'll go ahead and notify any clients waiting on the invoice
1290
        // state changes.
1291
        if updateSubscribers {
6✔
1292
                // We'll add a setID onto the notification, but only if this is
3✔
1293
                // an AMP invoice being settled.
3✔
1294
                var setID *[32]byte
3✔
1295
                if _, ok := resolution.(*HtlcSettleResolution); ok {
6✔
1296
                        setID = ctx.setID()
3✔
1297
                }
3✔
1298

1299
                i.notifyClients(ctx.hash, invoice, setID)
3✔
1300
        }
1301

1302
        return resolution, invoiceToExpire, nil
3✔
1303
}
1304

1305
// SettleHodlInvoice sets the preimage of a hodl invoice.
1306
func (i *InvoiceRegistry) SettleHodlInvoice(ctx context.Context,
1307
        preimage lntypes.Preimage) error {
3✔
1308

3✔
1309
        i.Lock()
3✔
1310
        defer i.Unlock()
3✔
1311

3✔
1312
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
6✔
1313
                switch invoice.State {
3✔
1314
                case ContractOpen:
×
1315
                        return nil, ErrInvoiceStillOpen
×
1316

1317
                case ContractCanceled:
×
1318
                        return nil, ErrInvoiceAlreadyCanceled
×
1319

1320
                case ContractSettled:
×
1321
                        return nil, ErrInvoiceAlreadySettled
×
1322
                }
1323

1324
                return &InvoiceUpdateDesc{
3✔
1325
                        UpdateType: SettleHodlInvoiceUpdate,
3✔
1326
                        State: &InvoiceStateUpdateDesc{
3✔
1327
                                NewState: ContractSettled,
3✔
1328
                                Preimage: &preimage,
3✔
1329
                        },
3✔
1330
                }, nil
3✔
1331
        }
1332

1333
        hash := preimage.Hash()
3✔
1334
        invoiceRef := InvoiceRefByHash(hash)
3✔
1335
        invoice, err := i.idb.UpdateInvoice(ctx, invoiceRef, nil, updateInvoice)
3✔
1336
        if err != nil {
3✔
1337
                log.Errorf("SettleHodlInvoice with preimage %v: %v",
×
1338
                        preimage, err)
×
1339

×
1340
                return err
×
1341
        }
×
1342

1343
        log.Debugf("Invoice%v: settled with preimage %v", invoiceRef,
3✔
1344
                invoice.Terms.PaymentPreimage)
3✔
1345

3✔
1346
        // In the callback, we marked the invoice as settled. UpdateInvoice will
3✔
1347
        // have seen this and should have moved all htlcs that were accepted to
3✔
1348
        // the settled state. In the loop below, we go through all of these and
3✔
1349
        // notify links and resolvers that are waiting for resolution. Any htlcs
3✔
1350
        // that were already settled before, will be notified again. This isn't
3✔
1351
        // necessary but doesn't hurt either.
3✔
1352
        for key, htlc := range invoice.Htlcs {
6✔
1353
                if htlc.State != HtlcStateSettled {
3✔
1354
                        continue
×
1355
                }
1356

1357
                resolution := NewSettleResolution(
3✔
1358
                        preimage, key, int32(htlc.AcceptHeight), ResultSettled,
3✔
1359
                )
3✔
1360

3✔
1361
                i.notifyHodlSubscribers(resolution)
3✔
1362
        }
1363
        i.notifyClients(hash, invoice, nil)
3✔
1364

3✔
1365
        return nil
3✔
1366
}
1367

1368
// CancelInvoice attempts to cancel the invoice corresponding to the passed
1369
// payment hash.
1370
func (i *InvoiceRegistry) CancelInvoice(ctx context.Context,
1371
        payHash lntypes.Hash) error {
3✔
1372

3✔
1373
        return i.cancelInvoiceImpl(ctx, payHash, true)
3✔
1374
}
3✔
1375

1376
// shouldCancel examines the state of an invoice and whether we want to
1377
// cancel already accepted invoices, taking our force cancel boolean into
1378
// account. This is pulled out into its own function so that tests that mock
1379
// cancelInvoiceImpl can reuse this logic.
1380
func shouldCancel(state ContractState, cancelAccepted bool) bool {
3✔
1381
        if state != ContractAccepted {
6✔
1382
                return true
3✔
1383
        }
3✔
1384

1385
        // If the invoice is accepted, we should only cancel if we want to
1386
        // force cancellation of accepted invoices.
1387
        return cancelAccepted
3✔
1388
}
1389

1390
// cancelInvoice attempts to cancel the invoice corresponding to the passed
1391
// payment hash. Accepted invoices will only be canceled if explicitly
1392
// requested to do so. It notifies subscribing links and resolvers that
1393
// the associated htlcs were canceled if they change state.
1394
func (i *InvoiceRegistry) cancelInvoiceImpl(ctx context.Context,
1395
        payHash lntypes.Hash, cancelAccepted bool) error {
3✔
1396

3✔
1397
        i.Lock()
3✔
1398
        defer i.Unlock()
3✔
1399

3✔
1400
        ref := InvoiceRefByHash(payHash)
3✔
1401
        log.Debugf("Invoice%v: canceling invoice", ref)
3✔
1402

3✔
1403
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
6✔
1404
                if !shouldCancel(invoice.State, cancelAccepted) {
3✔
1405
                        return nil, nil
×
1406
                }
×
1407

1408
                // Move invoice to the canceled state. Rely on validation in
1409
                // channeldb to return an error if the invoice is already
1410
                // settled or canceled.
1411
                return &InvoiceUpdateDesc{
3✔
1412
                        UpdateType: CancelInvoiceUpdate,
3✔
1413
                        State: &InvoiceStateUpdateDesc{
3✔
1414
                                NewState: ContractCanceled,
3✔
1415
                        },
3✔
1416
                }, nil
3✔
1417
        }
1418

1419
        invoiceRef := InvoiceRefByHash(payHash)
3✔
1420
        invoice, err := i.idb.UpdateInvoice(ctx, invoiceRef, nil, updateInvoice)
3✔
1421

3✔
1422
        // Implement idempotency by returning success if the invoice was already
3✔
1423
        // canceled.
3✔
1424
        if errors.Is(err, ErrInvoiceAlreadyCanceled) {
3✔
1425
                log.Debugf("Invoice%v: already canceled", ref)
×
1426
                return nil
×
1427
        }
×
1428
        if err != nil {
6✔
1429
                return err
3✔
1430
        }
3✔
1431

1432
        // Return without cancellation if the invoice state is ContractAccepted.
1433
        if invoice.State == ContractAccepted {
3✔
1434
                log.Debugf("Invoice%v: remains accepted as cancel wasn't"+
×
1435
                        "explicitly requested.", ref)
×
1436
                return nil
×
1437
        }
×
1438

1439
        log.Debugf("Invoice%v: canceled", ref)
3✔
1440

3✔
1441
        // In the callback, some htlcs may have been moved to the canceled
3✔
1442
        // state. We now go through all of these and notify links and resolvers
3✔
1443
        // that are waiting for resolution. Any htlcs that were already canceled
3✔
1444
        // before, will be notified again. This isn't necessary but doesn't hurt
3✔
1445
        // either.
3✔
1446
        for key, htlc := range invoice.Htlcs {
6✔
1447
                if htlc.State != HtlcStateCanceled {
3✔
1448
                        continue
×
1449
                }
1450

1451
                i.notifyHodlSubscribers(
3✔
1452
                        NewFailResolution(
3✔
1453
                                key, int32(htlc.AcceptHeight), ResultCanceled,
3✔
1454
                        ),
3✔
1455
                )
3✔
1456
        }
1457
        i.notifyClients(payHash, invoice, nil)
3✔
1458

3✔
1459
        // Attempt to also delete the invoice if requested through the registry
3✔
1460
        // config.
3✔
1461
        if i.cfg.GcCanceledInvoicesOnTheFly {
3✔
1462
                // Assemble the delete reference and attempt to delete through
×
1463
                // the invocice from the DB.
×
1464
                deleteRef := InvoiceDeleteRef{
×
1465
                        PayHash:     payHash,
×
1466
                        AddIndex:    invoice.AddIndex,
×
1467
                        SettleIndex: invoice.SettleIndex,
×
1468
                }
×
1469
                if invoice.Terms.PaymentAddr != BlankPayAddr {
×
1470
                        deleteRef.PayAddr = &invoice.Terms.PaymentAddr
×
1471
                }
×
1472

1473
                err = i.idb.DeleteInvoice(ctx, []InvoiceDeleteRef{deleteRef})
×
1474
                // If by any chance deletion failed, then log it instead of
×
1475
                // returning the error, as the invoice itself has already been
×
1476
                // canceled.
×
1477
                if err != nil {
×
1478
                        log.Warnf("Invoice %v could not be deleted: %v", ref,
×
1479
                                err)
×
1480
                }
×
1481
        }
1482

1483
        return nil
3✔
1484
}
1485

1486
// notifyClients notifies all currently registered invoice notification clients
1487
// of a newly added/settled invoice.
1488
func (i *InvoiceRegistry) notifyClients(hash lntypes.Hash,
1489
        invoice *Invoice, setID *[32]byte) {
3✔
1490

3✔
1491
        event := &invoiceEvent{
3✔
1492
                invoice: invoice,
3✔
1493
                hash:    hash,
3✔
1494
                setID:   setID,
3✔
1495
        }
3✔
1496

3✔
1497
        select {
3✔
1498
        case i.invoiceEvents <- event:
3✔
1499
        case <-i.quit:
×
1500
        }
1501
}
1502

1503
// invoiceSubscriptionKit defines that are common to both all invoice
1504
// subscribers and single invoice subscribers.
1505
type invoiceSubscriptionKit struct {
1506
        id uint32 // nolint:structcheck
1507

1508
        // quit is a chan mouted to InvoiceRegistry that signals a shutdown.
1509
        quit chan struct{}
1510

1511
        ntfnQueue *queue.ConcurrentQueue
1512

1513
        canceled   uint32 // To be used atomically.
1514
        cancelChan chan struct{}
1515

1516
        // backlogDelivered is closed when the backlog events have been
1517
        // delivered.
1518
        backlogDelivered chan struct{}
1519
}
1520

1521
// InvoiceSubscription represents an intent to receive updates for newly added
1522
// or settled invoices. For each newly added invoice, a copy of the invoice
1523
// will be sent over the NewInvoices channel. Similarly, for each newly settled
1524
// invoice, a copy of the invoice will be sent over the SettledInvoices
1525
// channel.
1526
type InvoiceSubscription struct {
1527
        invoiceSubscriptionKit
1528

1529
        // NewInvoices is a channel that we'll use to send all newly created
1530
        // invoices with an invoice index greater than the specified
1531
        // StartingInvoiceIndex field.
1532
        NewInvoices chan *Invoice
1533

1534
        // SettledInvoices is a channel that we'll use to send all settled
1535
        // invoices with an invoices index greater than the specified
1536
        // StartingInvoiceIndex field.
1537
        SettledInvoices chan *Invoice
1538

1539
        // addIndex is the highest add index the caller knows of. We'll use
1540
        // this information to send out an event backlog to the notifications
1541
        // subscriber. Any new add events with an index greater than this will
1542
        // be dispatched before any new notifications are sent out.
1543
        addIndex uint64
1544

1545
        // settleIndex is the highest settle index the caller knows of. We'll
1546
        // use this information to send out an event backlog to the
1547
        // notifications subscriber. Any new settle events with an index
1548
        // greater than this will be dispatched before any new notifications
1549
        // are sent out.
1550
        settleIndex uint64
1551
}
1552

1553
// SingleInvoiceSubscription represents an intent to receive updates for a
1554
// specific invoice.
1555
type SingleInvoiceSubscription struct {
1556
        invoiceSubscriptionKit
1557

1558
        invoiceRef InvoiceRef
1559

1560
        // Updates is a channel that we'll use to send all invoice events for
1561
        // the invoice that is subscribed to.
1562
        Updates chan *Invoice
1563
}
1564

1565
// PayHash returns the optional payment hash of the target invoice.
1566
//
1567
// TODO(positiveblue): This method is only supposed to be used in tests. It will
1568
// be deleted as soon as invoiceregistery_test is in the same module.
1569
func (s *SingleInvoiceSubscription) PayHash() *lntypes.Hash {
×
1570
        return s.invoiceRef.PayHash()
×
1571
}
×
1572

1573
// Cancel unregisters the InvoiceSubscription, freeing any previously allocated
1574
// resources.
1575
func (i *invoiceSubscriptionKit) Cancel() {
3✔
1576
        if !atomic.CompareAndSwapUint32(&i.canceled, 0, 1) {
3✔
1577
                return
×
1578
        }
×
1579

1580
        i.ntfnQueue.Stop()
3✔
1581
        close(i.cancelChan)
3✔
1582
}
1583

1584
func (i *invoiceSubscriptionKit) notify(event *invoiceEvent) error {
3✔
1585
        select {
3✔
1586
        case i.ntfnQueue.ChanIn() <- event:
3✔
1587

1588
        case <-i.cancelChan:
×
1589
                // This can only be triggered by delivery of non-backlog
×
1590
                // events.
×
1591
                return ErrShuttingDown
×
1592
        case <-i.quit:
×
1593
                return ErrShuttingDown
×
1594
        }
1595

1596
        return nil
3✔
1597
}
1598

1599
// SubscribeNotifications returns an InvoiceSubscription which allows the
1600
// caller to receive async notifications when any invoices are settled or
1601
// added. The invoiceIndex parameter is a streaming "checkpoint". We'll start
1602
// by first sending out all new events with an invoice index _greater_ than
1603
// this value. Afterwards, we'll send out real-time notifications.
1604
func (i *InvoiceRegistry) SubscribeNotifications(ctx context.Context,
1605
        addIndex, settleIndex uint64) (*InvoiceSubscription, error) {
3✔
1606

3✔
1607
        client := &InvoiceSubscription{
3✔
1608
                NewInvoices:     make(chan *Invoice),
3✔
1609
                SettledInvoices: make(chan *Invoice),
3✔
1610
                addIndex:        addIndex,
3✔
1611
                settleIndex:     settleIndex,
3✔
1612
                invoiceSubscriptionKit: invoiceSubscriptionKit{
3✔
1613
                        quit:             i.quit,
3✔
1614
                        ntfnQueue:        queue.NewConcurrentQueue(20),
3✔
1615
                        cancelChan:       make(chan struct{}),
3✔
1616
                        backlogDelivered: make(chan struct{}),
3✔
1617
                },
3✔
1618
        }
3✔
1619
        client.ntfnQueue.Start()
3✔
1620

3✔
1621
        // This notifies other goroutines that the backlog phase is over.
3✔
1622
        defer close(client.backlogDelivered)
3✔
1623

3✔
1624
        // Always increment by 1 first, and our client ID will start with 1,
3✔
1625
        // not 0.
3✔
1626
        client.id = atomic.AddUint32(&i.nextClientID, 1)
3✔
1627

3✔
1628
        // Before we register this new invoice subscription, we'll launch a new
3✔
1629
        // goroutine that will proxy all notifications appended to the end of
3✔
1630
        // the concurrent queue to the two client-side channels the caller will
3✔
1631
        // feed off of.
3✔
1632
        i.wg.Add(1)
3✔
1633
        go func() {
6✔
1634
                defer i.wg.Done()
3✔
1635
                defer i.deleteClient(client.id)
3✔
1636

3✔
1637
                for {
6✔
1638
                        select {
3✔
1639
                        // A new invoice event has been sent by the
1640
                        // invoiceRegistry! We'll figure out if this is an add
1641
                        // event or a settle event, then dispatch the event to
1642
                        // the client.
1643
                        case ntfn := <-client.ntfnQueue.ChanOut():
3✔
1644
                                invoiceEvent := ntfn.(*invoiceEvent)
3✔
1645

3✔
1646
                                var targetChan chan *Invoice
3✔
1647
                                state := invoiceEvent.invoice.State
3✔
1648
                                switch {
3✔
1649
                                // AMP invoices never move to settled, but will
1650
                                // be sent with a set ID if an HTLC set is
1651
                                // being settled.
1652
                                case state == ContractOpen &&
1653
                                        invoiceEvent.setID != nil:
3✔
1654
                                        fallthrough
3✔
1655

1656
                                case state == ContractSettled:
3✔
1657
                                        targetChan = client.SettledInvoices
3✔
1658

1659
                                case state == ContractOpen:
3✔
1660
                                        targetChan = client.NewInvoices
3✔
1661

1662
                                default:
×
1663
                                        log.Errorf("unknown invoice state: %v",
×
1664
                                                state)
×
1665

×
1666
                                        continue
×
1667
                                }
1668

1669
                                select {
3✔
1670
                                case targetChan <- invoiceEvent.invoice:
3✔
1671

1672
                                case <-client.cancelChan:
×
1673
                                        return
×
1674

1675
                                case <-i.quit:
×
1676
                                        return
×
1677
                                }
1678

1679
                        case <-client.cancelChan:
3✔
1680
                                return
3✔
1681

1682
                        case <-i.quit:
×
1683
                                return
×
1684
                        }
1685
                }
1686
        }()
1687

1688
        i.notificationClientMux.Lock()
3✔
1689
        i.notificationClients[client.id] = client
3✔
1690
        i.notificationClientMux.Unlock()
3✔
1691

3✔
1692
        // Query the database to see if based on the provided addIndex and
3✔
1693
        // settledIndex we need to deliver any backlog notifications.
3✔
1694
        err := i.deliverBacklogEvents(ctx, client)
3✔
1695
        if err != nil {
3✔
1696
                return nil, err
×
1697
        }
×
1698

1699
        log.Infof("New invoice subscription client: id=%v", client.id)
3✔
1700

3✔
1701
        return client, nil
3✔
1702
}
1703

1704
// SubscribeSingleInvoice returns an SingleInvoiceSubscription which allows the
1705
// caller to receive async notifications for a specific invoice.
1706
func (i *InvoiceRegistry) SubscribeSingleInvoice(ctx context.Context,
1707
        hash lntypes.Hash) (*SingleInvoiceSubscription, error) {
3✔
1708

3✔
1709
        client := &SingleInvoiceSubscription{
3✔
1710
                Updates: make(chan *Invoice),
3✔
1711
                invoiceSubscriptionKit: invoiceSubscriptionKit{
3✔
1712
                        quit:             i.quit,
3✔
1713
                        ntfnQueue:        queue.NewConcurrentQueue(20),
3✔
1714
                        cancelChan:       make(chan struct{}),
3✔
1715
                        backlogDelivered: make(chan struct{}),
3✔
1716
                },
3✔
1717
                invoiceRef: InvoiceRefByHash(hash),
3✔
1718
        }
3✔
1719
        client.ntfnQueue.Start()
3✔
1720

3✔
1721
        // This notifies other goroutines that the backlog phase is done.
3✔
1722
        defer close(client.backlogDelivered)
3✔
1723

3✔
1724
        // Always increment by 1 first, and our client ID will start with 1,
3✔
1725
        // not 0.
3✔
1726
        client.id = atomic.AddUint32(&i.nextClientID, 1)
3✔
1727

3✔
1728
        // Before we register this new invoice subscription, we'll launch a new
3✔
1729
        // goroutine that will proxy all notifications appended to the end of
3✔
1730
        // the concurrent queue to the two client-side channels the caller will
3✔
1731
        // feed off of.
3✔
1732
        i.wg.Add(1)
3✔
1733
        go func() {
6✔
1734
                defer i.wg.Done()
3✔
1735
                defer i.deleteClient(client.id)
3✔
1736

3✔
1737
                for {
6✔
1738
                        select {
3✔
1739
                        // A new invoice event has been sent by the
1740
                        // invoiceRegistry. We will dispatch the event to the
1741
                        // client.
1742
                        case ntfn := <-client.ntfnQueue.ChanOut():
3✔
1743
                                invoiceEvent := ntfn.(*invoiceEvent)
3✔
1744

3✔
1745
                                select {
3✔
1746
                                case client.Updates <- invoiceEvent.invoice:
3✔
1747

1748
                                case <-client.cancelChan:
×
1749
                                        return
×
1750

1751
                                case <-i.quit:
×
1752
                                        return
×
1753
                                }
1754

1755
                        case <-client.cancelChan:
3✔
1756
                                return
3✔
1757

1758
                        case <-i.quit:
×
1759
                                return
×
1760
                        }
1761
                }
1762
        }()
1763

1764
        i.notificationClientMux.Lock()
3✔
1765
        i.singleNotificationClients[client.id] = client
3✔
1766
        i.notificationClientMux.Unlock()
3✔
1767

3✔
1768
        err := i.deliverSingleBacklogEvents(ctx, client)
3✔
1769
        if err != nil {
3✔
1770
                return nil, err
×
1771
        }
×
1772

1773
        log.Infof("New single invoice subscription client: id=%v, ref=%v",
3✔
1774
                client.id, client.invoiceRef)
3✔
1775

3✔
1776
        return client, nil
3✔
1777
}
1778

1779
// notifyHodlSubscribers sends out the htlc resolution to all current
1780
// subscribers.
1781
func (i *InvoiceRegistry) notifyHodlSubscribers(htlcResolution HtlcResolution) {
3✔
1782
        i.hodlSubscriptionsMux.Lock()
3✔
1783
        defer i.hodlSubscriptionsMux.Unlock()
3✔
1784

3✔
1785
        subscribers, ok := i.hodlSubscriptions[htlcResolution.CircuitKey()]
3✔
1786
        if !ok {
6✔
1787
                return
3✔
1788
        }
3✔
1789

1790
        // Notify all interested subscribers and remove subscription from both
1791
        // maps. The subscription can be removed as there only ever will be a
1792
        // single resolution for each hash.
1793
        for subscriber := range subscribers {
6✔
1794
                select {
3✔
1795
                case subscriber <- htlcResolution:
3✔
1796
                case <-i.quit:
×
1797
                        return
×
1798
                }
1799

1800
                delete(
3✔
1801
                        i.hodlReverseSubscriptions[subscriber],
3✔
1802
                        htlcResolution.CircuitKey(),
3✔
1803
                )
3✔
1804
        }
1805

1806
        delete(i.hodlSubscriptions, htlcResolution.CircuitKey())
3✔
1807
}
1808

1809
// hodlSubscribe adds a new invoice subscription.
1810
func (i *InvoiceRegistry) hodlSubscribe(subscriber chan<- interface{},
1811
        circuitKey CircuitKey) {
3✔
1812

3✔
1813
        i.hodlSubscriptionsMux.Lock()
3✔
1814
        defer i.hodlSubscriptionsMux.Unlock()
3✔
1815

3✔
1816
        log.Debugf("Hodl subscribe for %v", circuitKey)
3✔
1817

3✔
1818
        subscriptions, ok := i.hodlSubscriptions[circuitKey]
3✔
1819
        if !ok {
6✔
1820
                subscriptions = make(map[chan<- interface{}]struct{})
3✔
1821
                i.hodlSubscriptions[circuitKey] = subscriptions
3✔
1822
        }
3✔
1823
        subscriptions[subscriber] = struct{}{}
3✔
1824

3✔
1825
        reverseSubscriptions, ok := i.hodlReverseSubscriptions[subscriber]
3✔
1826
        if !ok {
6✔
1827
                reverseSubscriptions = make(map[CircuitKey]struct{})
3✔
1828
                i.hodlReverseSubscriptions[subscriber] = reverseSubscriptions
3✔
1829
        }
3✔
1830
        reverseSubscriptions[circuitKey] = struct{}{}
3✔
1831
}
1832

1833
// HodlUnsubscribeAll cancels the subscription.
1834
func (i *InvoiceRegistry) HodlUnsubscribeAll(subscriber chan<- interface{}) {
3✔
1835
        i.hodlSubscriptionsMux.Lock()
3✔
1836
        defer i.hodlSubscriptionsMux.Unlock()
3✔
1837

3✔
1838
        hashes := i.hodlReverseSubscriptions[subscriber]
3✔
1839
        for hash := range hashes {
6✔
1840
                delete(i.hodlSubscriptions[hash], subscriber)
3✔
1841
        }
3✔
1842

1843
        delete(i.hodlReverseSubscriptions, subscriber)
3✔
1844
}
1845

1846
// copySingleClients copies i.SingleInvoiceSubscription inside a lock. This is
1847
// useful when we need to iterate the map to send notifications.
1848
func (i *InvoiceRegistry) copySingleClients() map[uint32]*SingleInvoiceSubscription { //nolint:ll
3✔
1849
        i.notificationClientMux.RLock()
3✔
1850
        defer i.notificationClientMux.RUnlock()
3✔
1851

3✔
1852
        clients := make(map[uint32]*SingleInvoiceSubscription)
3✔
1853
        for k, v := range i.singleNotificationClients {
6✔
1854
                clients[k] = v
3✔
1855
        }
3✔
1856
        return clients
3✔
1857
}
1858

1859
// copyClients copies i.notificationClients inside a lock. This is useful when
1860
// we need to iterate the map to send notifications.
1861
func (i *InvoiceRegistry) copyClients() map[uint32]*InvoiceSubscription {
3✔
1862
        i.notificationClientMux.RLock()
3✔
1863
        defer i.notificationClientMux.RUnlock()
3✔
1864

3✔
1865
        clients := make(map[uint32]*InvoiceSubscription)
3✔
1866
        for k, v := range i.notificationClients {
6✔
1867
                clients[k] = v
3✔
1868
        }
3✔
1869
        return clients
3✔
1870
}
1871

1872
// deleteClient removes a client by its ID inside a lock. Noop if the client is
1873
// not found.
1874
func (i *InvoiceRegistry) deleteClient(clientID uint32) {
3✔
1875
        i.notificationClientMux.Lock()
3✔
1876
        defer i.notificationClientMux.Unlock()
3✔
1877

3✔
1878
        log.Infof("Cancelling invoice subscription for client=%v", clientID)
3✔
1879
        delete(i.notificationClients, clientID)
3✔
1880
        delete(i.singleNotificationClients, clientID)
3✔
1881
}
3✔
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