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

lightningnetwork / lnd / 9840691252

08 Jul 2024 01:34PM UTC coverage: 58.404% (+0.08%) from 58.325%
9840691252

Pull #8900

github

guggero
Makefile: add GOCC variable
Pull Request #8900: Makefile: add GOCC variable

123350 of 211200 relevant lines covered (58.4%)

27929.2 hits per line

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

85.67
/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

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

85
        // key is the circuit key of the htlc to release.
86
        key CircuitKey
87

88
        // releaseTime is the time at which to release the htlc.
89
        releaseTime time.Time
90
}
91

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

100
// InvoiceRegistry is a central registry of all the outstanding invoices
101
// created by the daemon. The registry is a thin wrapper around a map in order
102
// to ensure that all updates/reads are thread safe.
103
type InvoiceRegistry struct {
104
        sync.RWMutex
105

106
        nextClientID uint32 // must be used atomically
107

108
        idb InvoiceDB
109

110
        // cfg contains the registry's configuration parameters.
111
        cfg *RegistryConfig
112

113
        // notificationClientMux locks notificationClients and
114
        // singleNotificationClients. Using a separate mutex for these maps is
115
        // necessary to avoid deadlocks in the registry when processing invoice
116
        // events.
117
        notificationClientMux sync.RWMutex
118

119
        notificationClients map[uint32]*InvoiceSubscription
120

121
        // TODO(yy): use map[lntypes.Hash]*SingleInvoiceSubscription for better
122
        // performance.
123
        singleNotificationClients map[uint32]*SingleInvoiceSubscription
124

125
        // invoiceEvents is a single channel over which invoice updates are
126
        // carried.
127
        invoiceEvents chan *invoiceEvent
128

129
        // hodlSubscriptionsMux locks the hodlSubscriptions and
130
        // hodlReverseSubscriptions. Using a separate mutex for these maps is
131
        // necessary to avoid deadlocks in the registry when processing invoice
132
        // events.
133
        hodlSubscriptionsMux sync.RWMutex
134

135
        // hodlSubscriptions is a map from a circuit key to a list of
136
        // subscribers. It is used for efficient notification of links.
137
        hodlSubscriptions map[CircuitKey]map[chan<- interface{}]struct{}
138

139
        // reverseSubscriptions tracks circuit keys subscribed to per
140
        // subscriber. This is used to unsubscribe from all hashes efficiently.
141
        hodlReverseSubscriptions map[chan<- interface{}]map[CircuitKey]struct{}
142

143
        // htlcAutoReleaseChan contains the new htlcs that need to be
144
        // auto-released.
145
        htlcAutoReleaseChan chan *htlcReleaseEvent
146

147
        expiryWatcher *InvoiceExpiryWatcher
148

149
        wg   sync.WaitGroup
150
        quit chan struct{}
151
}
152

153
// NewRegistry creates a new invoice registry. The invoice registry
154
// wraps the persistent on-disk invoice storage with an additional in-memory
155
// layer. The in-memory layer is in place such that debug invoices can be added
156
// which are volatile yet available system wide within the daemon.
157
func NewRegistry(idb InvoiceDB, expiryWatcher *InvoiceExpiryWatcher,
158
        cfg *RegistryConfig) *InvoiceRegistry {
638✔
159

638✔
160
        notificationClients := make(map[uint32]*InvoiceSubscription)
638✔
161
        singleNotificationClients := make(map[uint32]*SingleInvoiceSubscription)
638✔
162
        return &InvoiceRegistry{
638✔
163
                idb:                       idb,
638✔
164
                notificationClients:       notificationClients,
638✔
165
                singleNotificationClients: singleNotificationClients,
638✔
166
                invoiceEvents:             make(chan *invoiceEvent, 100),
638✔
167
                hodlSubscriptions: make(
638✔
168
                        map[CircuitKey]map[chan<- interface{}]struct{},
638✔
169
                ),
638✔
170
                hodlReverseSubscriptions: make(
638✔
171
                        map[chan<- interface{}]map[CircuitKey]struct{},
638✔
172
                ),
638✔
173
                cfg:                 cfg,
638✔
174
                htlcAutoReleaseChan: make(chan *htlcReleaseEvent),
638✔
175
                expiryWatcher:       expiryWatcher,
638✔
176
                quit:                make(chan struct{}),
638✔
177
        }
638✔
178
}
638✔
179

180
// scanInvoicesOnStart will scan all invoices on start and add active invoices
181
// to the invoice expiry watcher while also attempting to delete all canceled
182
// invoices.
183
func (i *InvoiceRegistry) scanInvoicesOnStart(ctx context.Context) error {
638✔
184
        pendingInvoices, err := i.idb.FetchPendingInvoices(ctx)
638✔
185
        if err != nil {
638✔
186
                return err
×
187
        }
×
188

189
        var pending []invoiceExpiry
638✔
190
        for paymentHash, invoice := range pendingInvoices {
672✔
191
                invoice := invoice
34✔
192
                expiryRef := makeInvoiceExpiry(paymentHash, &invoice)
34✔
193
                if expiryRef != nil {
68✔
194
                        pending = append(pending, expiryRef)
34✔
195
                }
34✔
196
        }
197

198
        log.Debugf("Adding %d pending invoices to the expiry watcher",
638✔
199
                len(pending))
638✔
200
        i.expiryWatcher.AddInvoices(pending...)
638✔
201

638✔
202
        if i.cfg.GcCanceledInvoicesOnStartup {
641✔
203
                log.Infof("Deleting canceled invoices")
3✔
204
                err = i.idb.DeleteCanceledInvoices(ctx)
3✔
205
                if err != nil {
3✔
206
                        log.Warnf("Deleting canceled invoices failed: %v", err)
×
207
                        return err
×
208
                }
×
209
        }
210

211
        return nil
638✔
212
}
213

214
// Start starts the registry and all goroutines it needs to carry out its task.
215
func (i *InvoiceRegistry) Start() error {
638✔
216
        // Start InvoiceExpiryWatcher and prepopulate it with existing active
638✔
217
        // invoices.
638✔
218
        err := i.expiryWatcher.Start(func(hash lntypes.Hash, force bool) error {
716✔
219
                return i.cancelInvoiceImpl(context.Background(), hash, force)
78✔
220
        })
78✔
221
        if err != nil {
638✔
222
                return err
×
223
        }
×
224

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

638✔
227
        i.wg.Add(1)
638✔
228
        go i.invoiceEventLoop()
638✔
229

638✔
230
        // Now scan all pending and removable invoices to the expiry watcher or
638✔
231
        // delete them.
638✔
232
        err = i.scanInvoicesOnStart(context.Background())
638✔
233
        if err != nil {
638✔
234
                _ = i.Stop()
×
235
                return err
×
236
        }
×
237

238
        return nil
638✔
239
}
240

241
// Stop signals the registry for a graceful shutdown.
242
func (i *InvoiceRegistry) Stop() error {
379✔
243
        log.Info("InvoiceRegistry shutting down...")
379✔
244
        defer log.Debug("InvoiceRegistry shutdown complete")
379✔
245

379✔
246
        i.expiryWatcher.Stop()
379✔
247

379✔
248
        close(i.quit)
379✔
249

379✔
250
        i.wg.Wait()
379✔
251
        return nil
379✔
252
}
379✔
253

254
// invoiceEvent represents a new event that has modified on invoice on disk.
255
// Only two event types are currently supported: newly created invoices, and
256
// instance where invoices are settled.
257
type invoiceEvent struct {
258
        hash    lntypes.Hash
259
        invoice *Invoice
260
        setID   *[32]byte
261
}
262

263
// tickAt returns a channel that ticks at the specified time. If the time has
264
// already passed, it will tick immediately.
265
func (i *InvoiceRegistry) tickAt(t time.Time) <-chan time.Time {
655✔
266
        now := i.cfg.Clock.Now()
655✔
267
        return i.cfg.Clock.TickAfter(t.Sub(now))
655✔
268
}
655✔
269

270
// invoiceEventLoop is the dedicated goroutine responsible for accepting
271
// new notification subscriptions, cancelling old subscriptions, and
272
// dispatching new invoice events.
273
func (i *InvoiceRegistry) invoiceEventLoop() {
638✔
274
        defer i.wg.Done()
638✔
275

638✔
276
        // Set up a heap for htlc auto-releases.
638✔
277
        autoReleaseHeap := &queue.PriorityQueue{}
638✔
278

638✔
279
        for {
4,307✔
280
                // If there is something to release, set up a release tick
3,669✔
281
                // channel.
3,669✔
282
                var nextReleaseTick <-chan time.Time
3,669✔
283
                if autoReleaseHeap.Len() > 0 {
4,324✔
284
                        head := autoReleaseHeap.Top().(*htlcReleaseEvent)
655✔
285
                        nextReleaseTick = i.tickAt(head.releaseTime)
655✔
286
                }
655✔
287

288
                select {
3,669✔
289
                // A sub-systems has just modified the invoice state, so we'll
290
                // dispatch notifications to all registered clients.
291
                case event := <-i.invoiceEvents:
2,693✔
292
                        // For backwards compatibility, do not notify all
2,693✔
293
                        // invoice subscribers of cancel and accept events.
2,693✔
294
                        state := event.invoice.State
2,693✔
295
                        if state != ContractCanceled &&
2,693✔
296
                                state != ContractAccepted {
4,797✔
297

2,104✔
298
                                i.dispatchToClients(event)
2,104✔
299
                        }
2,104✔
300
                        i.dispatchToSingleClients(event)
2,693✔
301

302
                // A new htlc came in for auto-release.
303
                case event := <-i.htlcAutoReleaseChan:
334✔
304
                        log.Debugf("Scheduling auto-release for htlc: "+
334✔
305
                                "ref=%v, key=%v at %v",
334✔
306
                                event.invoiceRef, event.key, event.releaseTime)
334✔
307

334✔
308
                        // We use an independent timer for every htlc rather
334✔
309
                        // than a set timer that is reset with every htlc coming
334✔
310
                        // in. Otherwise the sender could keep resetting the
334✔
311
                        // timer until the broadcast window is entered and our
334✔
312
                        // channel is force closed.
334✔
313
                        autoReleaseHeap.Push(event)
334✔
314

315
                // The htlc at the top of the heap needs to be auto-released.
316
                case <-nextReleaseTick:
12✔
317
                        event := autoReleaseHeap.Pop().(*htlcReleaseEvent)
12✔
318
                        err := i.cancelSingleHtlc(
12✔
319
                                event.invoiceRef, event.key, ResultMppTimeout,
12✔
320
                        )
12✔
321
                        if err != nil {
12✔
322
                                log.Errorf("HTLC timer: %v", err)
×
323
                        }
×
324

325
                case <-i.quit:
379✔
326
                        return
379✔
327
                }
328
        }
329
}
330

331
// dispatchToSingleClients passes the supplied event to all notification
332
// clients that subscribed to all the invoice this event applies to.
333
func (i *InvoiceRegistry) dispatchToSingleClients(event *invoiceEvent) {
2,693✔
334
        // Dispatch to single invoice subscribers.
2,693✔
335
        clients := i.copySingleClients()
2,693✔
336
        for _, client := range clients {
2,733✔
337
                payHash := client.invoiceRef.PayHash()
40✔
338

40✔
339
                if payHash == nil || *payHash != event.hash {
44✔
340
                        continue
4✔
341
                }
342

343
                select {
40✔
344
                case <-client.backlogDelivered:
40✔
345
                        // We won't deliver any events until the backlog has
346
                        // went through first.
347
                case <-i.quit:
×
348
                        return
×
349
                }
350

351
                client.notify(event)
40✔
352
        }
353
}
354

355
// dispatchToClients passes the supplied event to all notification clients that
356
// subscribed to all invoices. Add and settle indices are used to make sure
357
// that clients don't receive duplicate or unwanted events.
358
func (i *InvoiceRegistry) dispatchToClients(event *invoiceEvent) {
2,104✔
359
        invoice := event.invoice
2,104✔
360

2,104✔
361
        clients := i.copyClients()
2,104✔
362
        for clientID, client := range clients {
2,174✔
363
                // Before we dispatch this event, we'll check
70✔
364
                // to ensure that this client hasn't already
70✔
365
                // received this notification in order to
70✔
366
                // ensure we don't duplicate any events.
70✔
367

70✔
368
                // TODO(joostjager): Refactor switches.
70✔
369
                state := event.invoice.State
70✔
370
                switch {
70✔
371
                // If we've already sent this settle event to
372
                // the client, then we can skip this.
373
                case state == ContractSettled &&
374
                        client.settleIndex >= invoice.SettleIndex:
×
375
                        continue
×
376

377
                // Similarly, if we've already sent this add to
378
                // the client then we can skip this one, but only if this isn't
379
                // an AMP invoice. AMP invoices always remain in the settle
380
                // state as a base invoice.
381
                case event.setID == nil && state == ContractOpen &&
382
                        client.addIndex >= invoice.AddIndex:
×
383
                        continue
×
384

385
                // These two states should never happen, but we
386
                // log them just in case so we can detect this
387
                // instance.
388
                case state == ContractOpen &&
389
                        client.addIndex+1 != invoice.AddIndex:
11✔
390
                        log.Warnf("client=%v for invoice "+
11✔
391
                                "notifications missed an update, "+
11✔
392
                                "add_index=%v, new add event index=%v",
11✔
393
                                clientID, client.addIndex,
11✔
394
                                invoice.AddIndex)
11✔
395

396
                case state == ContractSettled &&
397
                        client.settleIndex+1 != invoice.SettleIndex:
4✔
398
                        log.Warnf("client=%v for invoice "+
4✔
399
                                "notifications missed an update, "+
4✔
400
                                "settle_index=%v, new settle event index=%v",
4✔
401
                                clientID, client.settleIndex,
4✔
402
                                invoice.SettleIndex)
4✔
403
                }
404

405
                select {
70✔
406
                case <-client.backlogDelivered:
70✔
407
                        // We won't deliver any events until the backlog has
408
                        // been processed.
409
                case <-i.quit:
×
410
                        return
×
411
                }
412

413
                err := client.notify(&invoiceEvent{
70✔
414
                        invoice: invoice,
70✔
415
                        setID:   event.setID,
70✔
416
                })
70✔
417
                if err != nil {
70✔
418
                        log.Errorf("Failed dispatching to client: %v", err)
×
419
                        return
×
420
                }
×
421

422
                // Each time we send a notification to a client, we'll record
423
                // the latest add/settle index it has. We'll use this to ensure
424
                // we don't send a notification twice, which can happen if a new
425
                // event is added while we're catching up a new client.
426
                invState := event.invoice.State
70✔
427
                switch {
70✔
428
                case invState == ContractSettled:
22✔
429
                        client.settleIndex = invoice.SettleIndex
22✔
430

431
                case invState == ContractOpen && event.setID == nil:
46✔
432
                        client.addIndex = invoice.AddIndex
46✔
433

434
                // If this is an AMP invoice, then we'll need to use the set ID
435
                // to keep track of the settle index of the client. AMP
436
                // invoices never go to the open state, but if a setID is
437
                // passed, then we know it was just settled and will track the
438
                // highest settle index so far.
439
                case invState == ContractOpen && event.setID != nil:
10✔
440
                        setID := *event.setID
10✔
441
                        client.settleIndex = invoice.AMPState[setID].SettleIndex
10✔
442

443
                default:
×
444
                        log.Errorf("unexpected invoice state: %v",
×
445
                                event.invoice.State)
×
446
                }
447
        }
448
}
449

450
// deliverBacklogEvents will attempts to query the invoice database for any
451
// notifications that the client has missed since it reconnected last.
452
func (i *InvoiceRegistry) deliverBacklogEvents(ctx context.Context,
453
        client *InvoiceSubscription) error {
49✔
454

49✔
455
        addEvents, err := i.idb.InvoicesAddedSince(ctx, client.addIndex)
49✔
456
        if err != nil {
49✔
457
                return err
×
458
        }
×
459

460
        settleEvents, err := i.idb.InvoicesSettledSince(ctx, client.settleIndex)
49✔
461
        if err != nil {
49✔
462
                return err
×
463
        }
×
464

465
        // If we have any to deliver, then we'll append them to the end of the
466
        // notification queue in order to catch up the client before delivering
467
        // any new notifications.
468
        for _, addEvent := range addEvents {
53✔
469
                // We re-bind the loop variable to ensure we don't hold onto
4✔
470
                // the loop reference causing is to point to the same item.
4✔
471
                addEvent := addEvent
4✔
472

4✔
473
                select {
4✔
474
                case client.ntfnQueue.ChanIn() <- &invoiceEvent{
475
                        invoice: &addEvent,
476
                }:
4✔
477
                case <-i.quit:
×
478
                        return ErrShuttingDown
×
479
                }
480
        }
481

482
        for _, settleEvent := range settleEvents {
53✔
483
                // We re-bind the loop variable to ensure we don't hold onto
4✔
484
                // the loop reference causing is to point to the same item.
4✔
485
                settleEvent := settleEvent
4✔
486

4✔
487
                select {
4✔
488
                case client.ntfnQueue.ChanIn() <- &invoiceEvent{
489
                        invoice: &settleEvent,
490
                }:
4✔
491
                case <-i.quit:
×
492
                        return ErrShuttingDown
×
493
                }
494
        }
495

496
        return nil
49✔
497
}
498

499
// deliverSingleBacklogEvents will attempt to query the invoice database to
500
// retrieve the current invoice state and deliver this to the subscriber. Single
501
// invoice subscribers will always receive the current state right after
502
// subscribing. Only in case the invoice does not yet exist, nothing is sent
503
// yet.
504
func (i *InvoiceRegistry) deliverSingleBacklogEvents(ctx context.Context,
505
        client *SingleInvoiceSubscription) error {
22✔
506

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

22✔
509
        // It is possible that the invoice does not exist yet, but the client is
22✔
510
        // already watching it in anticipation.
22✔
511
        isNotFound := errors.Is(err, ErrInvoiceNotFound)
22✔
512
        isNotCreated := errors.Is(err, ErrNoInvoicesCreated)
22✔
513
        if isNotFound || isNotCreated {
44✔
514
                return nil
22✔
515
        }
22✔
516
        if err != nil {
4✔
517
                return err
×
518
        }
×
519

520
        payHash := client.invoiceRef.PayHash()
4✔
521
        if payHash == nil {
4✔
522
                return nil
×
523
        }
×
524

525
        err = client.notify(&invoiceEvent{
4✔
526
                hash:    *payHash,
4✔
527
                invoice: &invoice,
4✔
528
        })
4✔
529
        if err != nil {
4✔
530
                return err
×
531
        }
×
532

533
        log.Debugf("Client(id=%v) delivered single backlog event: payHash=%v",
4✔
534
                client.id, payHash)
4✔
535

4✔
536
        return nil
4✔
537
}
538

539
// AddInvoice adds a regular invoice for the specified amount, identified by
540
// the passed preimage. Additionally, any memo or receipt data provided will
541
// also be stored on-disk. Once this invoice is added, subsystems within the
542
// daemon add/forward HTLCs are able to obtain the proper preimage required for
543
// redemption in the case that we're the final destination. We also return the
544
// addIndex of the newly created invoice which monotonically increases for each
545
// new invoice added.  A side effect of this function is that it also sets
546
// AddIndex on the invoice argument.
547
func (i *InvoiceRegistry) AddInvoice(ctx context.Context, invoice *Invoice,
548
        paymentHash lntypes.Hash) (uint64, error) {
1,156✔
549

1,156✔
550
        i.Lock()
1,156✔
551

1,156✔
552
        ref := InvoiceRefByHash(paymentHash)
1,156✔
553
        log.Debugf("Invoice%v: added with terms %v", ref, invoice.Terms)
1,156✔
554

1,156✔
555
        addIndex, err := i.idb.AddInvoice(ctx, invoice, paymentHash)
1,156✔
556
        if err != nil {
1,175✔
557
                i.Unlock()
19✔
558
                return 0, err
19✔
559
        }
19✔
560

561
        // Now that we've added the invoice, we'll send dispatch a message to
562
        // notify the clients of this new invoice.
563
        i.notifyClients(paymentHash, invoice, nil)
1,141✔
564
        i.Unlock()
1,141✔
565

1,141✔
566
        // InvoiceExpiryWatcher.AddInvoice must not be locked by InvoiceRegistry
1,141✔
567
        // to avoid deadlock when a new invoice is added while an other is being
1,141✔
568
        // canceled.
1,141✔
569
        invoiceExpiryRef := makeInvoiceExpiry(paymentHash, invoice)
1,141✔
570
        if invoiceExpiryRef != nil {
2,282✔
571
                i.expiryWatcher.AddInvoices(invoiceExpiryRef)
1,141✔
572
        }
1,141✔
573

574
        return addIndex, nil
1,141✔
575
}
576

577
// LookupInvoice looks up an invoice by its payment hash (R-Hash), if found
578
// then we're able to pull the funds pending within an HTLC.
579
//
580
// TODO(roasbeef): ignore if settled?
581
func (i *InvoiceRegistry) LookupInvoice(ctx context.Context,
582
        rHash lntypes.Hash) (Invoice, error) {
399✔
583

399✔
584
        // We'll check the database to see if there's an existing matching
399✔
585
        // invoice.
399✔
586
        ref := InvoiceRefByHash(rHash)
399✔
587
        return i.idb.LookupInvoice(ctx, ref)
399✔
588
}
399✔
589

590
// LookupInvoiceByRef looks up an invoice by the given reference, if found
591
// then we're able to pull the funds pending within an HTLC.
592
func (i *InvoiceRegistry) LookupInvoiceByRef(ctx context.Context,
593
        ref InvoiceRef) (Invoice, error) {
4✔
594

4✔
595
        return i.idb.LookupInvoice(ctx, ref)
4✔
596
}
4✔
597

598
// startHtlcTimer starts a new timer via the invoice registry main loop that
599
// cancels a single htlc on an invoice when the htlc hold duration has passed.
600
func (i *InvoiceRegistry) startHtlcTimer(invoiceRef InvoiceRef,
601
        key CircuitKey, acceptTime time.Time) error {
334✔
602

334✔
603
        releaseTime := acceptTime.Add(i.cfg.HtlcHoldDuration)
334✔
604
        event := &htlcReleaseEvent{
334✔
605
                invoiceRef:  invoiceRef,
334✔
606
                key:         key,
334✔
607
                releaseTime: releaseTime,
334✔
608
        }
334✔
609

334✔
610
        select {
334✔
611
        case i.htlcAutoReleaseChan <- event:
334✔
612
                return nil
334✔
613

614
        case <-i.quit:
×
615
                return ErrShuttingDown
×
616
        }
617
}
618

619
// cancelSingleHtlc cancels a single accepted htlc on an invoice. It takes
620
// a resolution result which will be used to notify subscribed links and
621
// resolvers of the details of the htlc cancellation.
622
func (i *InvoiceRegistry) cancelSingleHtlc(invoiceRef InvoiceRef,
623
        key CircuitKey, result FailResolutionResult) error {
12✔
624

12✔
625
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
24✔
626
                // Only allow individual htlc cancellation on open invoices.
12✔
627
                if invoice.State != ContractOpen {
18✔
628
                        log.Debugf("cancelSingleHtlc: invoice %v no longer "+
6✔
629
                                "open", invoiceRef)
6✔
630

6✔
631
                        return nil, nil
6✔
632
                }
6✔
633

634
                // Lookup the current status of the htlc in the database.
635
                var (
6✔
636
                        htlcState HtlcState
6✔
637
                        setID     *SetID
6✔
638
                )
6✔
639
                htlc, ok := invoice.Htlcs[key]
6✔
640
                if !ok {
6✔
641
                        // If this is an AMP invoice, then all the HTLCs won't
×
642
                        // be read out, so we'll consult the other mapping to
×
643
                        // try to find the HTLC state in question here.
×
644
                        var found bool
×
645
                        for ampSetID, htlcSet := range invoice.AMPState {
×
646
                                ampSetID := ampSetID
×
647
                                for htlcKey := range htlcSet.InvoiceKeys {
×
648
                                        if htlcKey == key {
×
649
                                                htlcState = htlcSet.State
×
650
                                                setID = &ampSetID
×
651

×
652
                                                found = true
×
653
                                                break
×
654
                                        }
655
                                }
656
                        }
657

658
                        if !found {
×
659
                                return nil, fmt.Errorf("htlc %v not found", key)
×
660
                        }
×
661
                } else {
6✔
662
                        htlcState = htlc.State
6✔
663
                }
6✔
664

665
                // Cancellation is only possible if the htlc wasn't already
666
                // resolved.
667
                if htlcState != HtlcStateAccepted {
6✔
668
                        log.Debugf("cancelSingleHtlc: htlc %v on invoice %v "+
×
669
                                "is already resolved", key, invoiceRef)
×
670

×
671
                        return nil, nil
×
672
                }
×
673

674
                log.Debugf("cancelSingleHtlc: cancelling htlc %v on invoice %v",
6✔
675
                        key, invoiceRef)
6✔
676

6✔
677
                // Return an update descriptor that cancels htlc and keeps
6✔
678
                // invoice open.
6✔
679
                canceledHtlcs := map[CircuitKey]struct{}{
6✔
680
                        key: {},
6✔
681
                }
6✔
682

6✔
683
                return &InvoiceUpdateDesc{
6✔
684
                        UpdateType:  CancelHTLCsUpdate,
6✔
685
                        CancelHtlcs: canceledHtlcs,
6✔
686
                        SetID:       setID,
6✔
687
                }, nil
6✔
688
        }
689

690
        // Try to mark the specified htlc as canceled in the invoice database.
691
        // Intercept the update descriptor to set the local updated variable. If
692
        // no invoice update is performed, we can return early.
693
        setID := (*SetID)(invoiceRef.SetID())
12✔
694
        var updated bool
12✔
695
        invoice, err := i.idb.UpdateInvoice(
12✔
696
                context.Background(), invoiceRef, setID,
12✔
697
                func(invoice *Invoice) (
12✔
698
                        *InvoiceUpdateDesc, error) {
24✔
699

12✔
700
                        updateDesc, err := updateInvoice(invoice)
12✔
701
                        if err != nil {
12✔
702
                                return nil, err
×
703
                        }
×
704
                        updated = updateDesc != nil
12✔
705

12✔
706
                        return updateDesc, err
12✔
707
                },
708
        )
709
        if err != nil {
12✔
710
                return err
×
711
        }
×
712
        if !updated {
18✔
713
                return nil
6✔
714
        }
6✔
715

716
        // The invoice has been updated. Notify subscribers of the htlc
717
        // resolution.
718
        htlc, ok := invoice.Htlcs[key]
6✔
719
        if !ok {
6✔
720
                return fmt.Errorf("htlc %v not found", key)
×
721
        }
×
722
        if htlc.State == HtlcStateCanceled {
12✔
723
                resolution := NewFailResolution(
6✔
724
                        key, int32(htlc.AcceptHeight), result,
6✔
725
                )
6✔
726

6✔
727
                i.notifyHodlSubscribers(resolution)
6✔
728
        }
6✔
729
        return nil
6✔
730
}
731

732
// processKeySend just-in-time inserts an invoice if this htlc is a keysend
733
// htlc.
734
func (i *InvoiceRegistry) processKeySend(ctx invoiceUpdateCtx) error {
22✔
735
        // Retrieve keysend record if present.
22✔
736
        preimageSlice, ok := ctx.customRecords[record.KeySendType]
22✔
737
        if !ok {
26✔
738
                return nil
4✔
739
        }
4✔
740

741
        // Cancel htlc is preimage is invalid.
742
        preimage, err := lntypes.MakePreimage(preimageSlice)
22✔
743
        if err != nil {
25✔
744
                return err
3✔
745
        }
3✔
746
        if preimage.Hash() != ctx.hash {
19✔
747
                return fmt.Errorf("invalid keysend preimage %v for hash %v",
×
748
                        preimage, ctx.hash)
×
749
        }
×
750

751
        // Only allow keysend for non-mpp payments.
752
        if ctx.mpp != nil {
19✔
753
                return errors.New("no mpp keysend supported")
×
754
        }
×
755

756
        // Create an invoice for the htlc amount.
757
        amt := ctx.amtPaid
19✔
758

19✔
759
        // Set tlv required feature vector on the invoice. Otherwise we wouldn't
19✔
760
        // be able to pay to it with keysend.
19✔
761
        rawFeatures := lnwire.NewRawFeatureVector(
19✔
762
                lnwire.TLVOnionPayloadRequired,
19✔
763
        )
19✔
764
        features := lnwire.NewFeatureVector(rawFeatures, lnwire.Features)
19✔
765

19✔
766
        // Use the minimum block delta that we require for settling htlcs.
19✔
767
        finalCltvDelta := i.cfg.FinalCltvRejectDelta
19✔
768

19✔
769
        // Pre-check expiry here to prevent inserting an invoice that will not
19✔
770
        // be settled.
19✔
771
        if ctx.expiry < uint32(ctx.currentHeight+finalCltvDelta) {
19✔
772
                return errors.New("final expiry too soon")
×
773
        }
×
774

775
        // The invoice database indexes all invoices by payment address, however
776
        // legacy keysend payment do not have one. In order to avoid a new
777
        // payment type on-disk wrt. to indexing, we'll continue to insert a
778
        // blank payment address which is special cased in the insertion logic
779
        // to not be indexed. In the future, once AMP is merged, this should be
780
        // replaced by generating a random payment address on the behalf of the
781
        // sender.
782
        payAddr := BlankPayAddr
19✔
783

19✔
784
        // Create placeholder invoice.
19✔
785
        invoice := &Invoice{
19✔
786
                CreationDate: i.cfg.Clock.Now(),
19✔
787
                Terms: ContractTerm{
19✔
788
                        FinalCltvDelta:  finalCltvDelta,
19✔
789
                        Value:           amt,
19✔
790
                        PaymentPreimage: &preimage,
19✔
791
                        PaymentAddr:     payAddr,
19✔
792
                        Features:        features,
19✔
793
                },
19✔
794
        }
19✔
795

19✔
796
        if i.cfg.KeysendHoldTime != 0 {
25✔
797
                invoice.HodlInvoice = true
6✔
798
                invoice.Terms.Expiry = i.cfg.KeysendHoldTime
6✔
799
        }
6✔
800

801
        // Insert invoice into database. Ignore duplicates, because this
802
        // may be a replay.
803
        _, err = i.AddInvoice(context.Background(), invoice, ctx.hash)
19✔
804
        if err != nil && !errors.Is(err, ErrDuplicateInvoice) {
19✔
805
                return err
×
806
        }
×
807

808
        return nil
19✔
809
}
810

811
// processAMP just-in-time inserts an invoice if this htlc is a keysend
812
// htlc.
813
func (i *InvoiceRegistry) processAMP(ctx invoiceUpdateCtx) error {
31✔
814
        // AMP payments MUST also include an MPP record.
31✔
815
        if ctx.mpp == nil {
34✔
816
                return errors.New("no MPP record for AMP")
3✔
817
        }
3✔
818

819
        // Create an invoice for the total amount expected, provided in the MPP
820
        // record.
821
        amt := ctx.mpp.TotalMsat()
28✔
822

28✔
823
        // Set the TLV required and MPP optional features on the invoice. We'll
28✔
824
        // also make the AMP features required so that it can't be paid by
28✔
825
        // legacy or MPP htlcs.
28✔
826
        rawFeatures := lnwire.NewRawFeatureVector(
28✔
827
                lnwire.TLVOnionPayloadRequired,
28✔
828
                lnwire.PaymentAddrOptional,
28✔
829
                lnwire.AMPRequired,
28✔
830
        )
28✔
831
        features := lnwire.NewFeatureVector(rawFeatures, lnwire.Features)
28✔
832

28✔
833
        // Use the minimum block delta that we require for settling htlcs.
28✔
834
        finalCltvDelta := i.cfg.FinalCltvRejectDelta
28✔
835

28✔
836
        // Pre-check expiry here to prevent inserting an invoice that will not
28✔
837
        // be settled.
28✔
838
        if ctx.expiry < uint32(ctx.currentHeight+finalCltvDelta) {
28✔
839
                return errors.New("final expiry too soon")
×
840
        }
×
841

842
        // We'll use the sender-generated payment address provided in the HTLC
843
        // to create our AMP invoice.
844
        payAddr := ctx.mpp.PaymentAddr()
28✔
845

28✔
846
        // Create placeholder invoice.
28✔
847
        invoice := &Invoice{
28✔
848
                CreationDate: i.cfg.Clock.Now(),
28✔
849
                Terms: ContractTerm{
28✔
850
                        FinalCltvDelta:  finalCltvDelta,
28✔
851
                        Value:           amt,
28✔
852
                        PaymentPreimage: nil,
28✔
853
                        PaymentAddr:     payAddr,
28✔
854
                        Features:        features,
28✔
855
                },
28✔
856
        }
28✔
857

28✔
858
        // Insert invoice into database. Ignore duplicates payment hashes and
28✔
859
        // payment addrs, this may be a replay or a different HTLC for the AMP
28✔
860
        // invoice.
28✔
861
        _, err := i.AddInvoice(context.Background(), invoice, ctx.hash)
28✔
862
        isDuplicatedInvoice := errors.Is(err, ErrDuplicateInvoice)
28✔
863
        isDuplicatedPayAddr := errors.Is(err, ErrDuplicatePayAddr)
28✔
864
        switch {
28✔
865
        case isDuplicatedInvoice || isDuplicatedPayAddr:
16✔
866
                return nil
16✔
867
        default:
16✔
868
                return err
16✔
869
        }
870
}
871

872
// NotifyExitHopHtlc attempts to mark an invoice as settled. The return value
873
// describes how the htlc should be resolved.
874
//
875
// When the preimage of the invoice is not yet known (hodl invoice), this
876
// function moves the invoice to the accepted state. When SettleHoldInvoice is
877
// called later, a resolution message will be send back to the caller via the
878
// provided hodlChan. Invoice registry sends on this channel what action needs
879
// to be taken on the htlc (settle or cancel). The caller needs to ensure that
880
// the channel is either buffered or received on from another goroutine to
881
// prevent deadlock.
882
//
883
// In the case that the htlc is part of a larger set of htlcs that pay to the
884
// same invoice (multi-path payment), the htlc is held until the set is
885
// complete. If the set doesn't fully arrive in time, a timer will cancel the
886
// held htlc.
887
func (i *InvoiceRegistry) NotifyExitHopHtlc(rHash lntypes.Hash,
888
        amtPaid lnwire.MilliSatoshi, expiry uint32, currentHeight int32,
889
        circuitKey CircuitKey, hodlChan chan<- interface{},
890
        payload Payload) (HtlcResolution, error) {
1,383✔
891

1,383✔
892
        // Create the update context containing the relevant details of the
1,383✔
893
        // incoming htlc.
1,383✔
894
        ctx := invoiceUpdateCtx{
1,383✔
895
                hash:                 rHash,
1,383✔
896
                circuitKey:           circuitKey,
1,383✔
897
                amtPaid:              amtPaid,
1,383✔
898
                expiry:               expiry,
1,383✔
899
                currentHeight:        currentHeight,
1,383✔
900
                finalCltvRejectDelta: i.cfg.FinalCltvRejectDelta,
1,383✔
901
                customRecords:        payload.CustomRecords(),
1,383✔
902
                mpp:                  payload.MultiPath(),
1,383✔
903
                amp:                  payload.AMPRecord(),
1,383✔
904
                metadata:             payload.Metadata(),
1,383✔
905
        }
1,383✔
906

1,383✔
907
        switch {
1,383✔
908
        // If we are accepting spontaneous AMP payments and this payload
909
        // contains an AMP record, create an AMP invoice that will be settled
910
        // below.
911
        case i.cfg.AcceptAMP && ctx.amp != nil:
31✔
912
                err := i.processAMP(ctx)
31✔
913
                if err != nil {
34✔
914
                        ctx.log(fmt.Sprintf("amp error: %v", err))
3✔
915

3✔
916
                        return NewFailResolution(
3✔
917
                                circuitKey, currentHeight, ResultAmpError,
3✔
918
                        ), nil
3✔
919
                }
3✔
920

921
        // If we are accepting spontaneous keysend payments, create a regular
922
        // invoice that will be settled below. We also enforce that this is only
923
        // done when no AMP payload is present since it will only be settle-able
924
        // by regular HTLCs.
925
        case i.cfg.AcceptKeySend && ctx.amp == nil:
22✔
926
                err := i.processKeySend(ctx)
22✔
927
                if err != nil {
25✔
928
                        ctx.log(fmt.Sprintf("keysend error: %v", err))
3✔
929

3✔
930
                        return NewFailResolution(
3✔
931
                                circuitKey, currentHeight, ResultKeySendError,
3✔
932
                        ), nil
3✔
933
                }
3✔
934
        }
935

936
        // Execute locked notify exit hop logic.
937
        i.Lock()
1,377✔
938
        resolution, invoiceToExpire, err := i.notifyExitHopHtlcLocked(
1,377✔
939
                &ctx, hodlChan,
1,377✔
940
        )
1,377✔
941
        i.Unlock()
1,377✔
942
        if err != nil {
1,377✔
943
                return nil, err
×
944
        }
×
945

946
        if invoiceToExpire != nil {
1,896✔
947
                i.expiryWatcher.AddInvoices(invoiceToExpire)
519✔
948
        }
519✔
949

950
        switch r := resolution.(type) {
1,377✔
951
        // The htlc is held. Start a timer outside the lock if the htlc should
952
        // be auto-released, because otherwise a deadlock may happen with the
953
        // main event loop.
954
        case *htlcAcceptResolution:
856✔
955
                if r.autoRelease {
1,190✔
956
                        var invRef InvoiceRef
334✔
957
                        if ctx.amp != nil {
350✔
958
                                invRef = InvoiceRefBySetID(*ctx.setID())
16✔
959
                        } else {
338✔
960
                                invRef = ctx.invoiceRef()
322✔
961
                        }
322✔
962

963
                        err := i.startHtlcTimer(
334✔
964
                                invRef, circuitKey, r.acceptTime,
334✔
965
                        )
334✔
966
                        if err != nil {
334✔
967
                                return nil, err
×
968
                        }
×
969
                }
970

971
                // We return a nil resolution because htlc acceptances are
972
                // represented as nil resolutions externally.
973
                // TODO(carla) update calling code to handle accept resolutions.
974
                return nil, nil
856✔
975

976
        // A direct resolution was received for this htlc.
977
        case HtlcResolution:
525✔
978
                return r, nil
525✔
979

980
        // Fail if an unknown resolution type was received.
981
        default:
×
982
                return nil, errors.New("invalid resolution type")
×
983
        }
984
}
985

986
// notifyExitHopHtlcLocked is the internal implementation of NotifyExitHopHtlc
987
// that should be executed inside the registry lock. The returned invoiceExpiry
988
// (if not nil) needs to be added to the expiry watcher outside of the lock.
989
func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
990
        ctx *invoiceUpdateCtx, hodlChan chan<- interface{}) (
991
        HtlcResolution, invoiceExpiry, error) {
1,377✔
992

1,377✔
993
        // We'll attempt to settle an invoice matching this rHash on disk (if
1,377✔
994
        // one exists). The callback will update the invoice state and/or htlcs.
1,377✔
995
        var (
1,377✔
996
                resolution        HtlcResolution
1,377✔
997
                updateSubscribers bool
1,377✔
998
        )
1,377✔
999

1,377✔
1000
        callback := func(inv *Invoice) (*InvoiceUpdateDesc, error) {
2,732✔
1001
                updateDesc, res, err := updateInvoice(ctx, inv)
1,355✔
1002
                if err != nil {
1,355✔
1003
                        return nil, err
×
1004
                }
×
1005

1006
                // Only send an update if the invoice state was changed.
1007
                updateSubscribers = updateDesc != nil &&
1,355✔
1008
                        updateDesc.State != nil
1,355✔
1009

1,355✔
1010
                // Assign resolution to outer scope variable.
1,355✔
1011
                resolution = res
1,355✔
1012

1,355✔
1013
                return updateDesc, nil
1,355✔
1014
        }
1015

1016
        invoiceRef := ctx.invoiceRef()
1,377✔
1017
        setID := (*SetID)(ctx.setID())
1,377✔
1018
        invoice, err := i.idb.UpdateInvoice(
1,377✔
1019
                context.Background(), invoiceRef, setID, callback,
1,377✔
1020
        )
1,377✔
1021

1,377✔
1022
        var duplicateSetIDErr ErrDuplicateSetID
1,377✔
1023
        if errors.As(err, &duplicateSetIDErr) {
1,377✔
1024
                return NewFailResolution(
×
1025
                        ctx.circuitKey, ctx.currentHeight,
×
1026
                        ResultInvoiceNotFound,
×
1027
                ), nil, nil
×
1028
        }
×
1029

1030
        switch err {
1,377✔
1031
        case ErrInvoiceNotFound:
26✔
1032
                // If the invoice was not found, return a failure resolution
26✔
1033
                // with an invoice not found result.
26✔
1034
                return NewFailResolution(
26✔
1035
                        ctx.circuitKey, ctx.currentHeight,
26✔
1036
                        ResultInvoiceNotFound,
26✔
1037
                ), nil, nil
26✔
1038

1039
        case ErrInvRefEquivocation:
×
1040
                return NewFailResolution(
×
1041
                        ctx.circuitKey, ctx.currentHeight,
×
1042
                        ResultInvoiceNotFound,
×
1043
                ), nil, nil
×
1044

1045
        case nil:
1,355✔
1046

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

1052
        var invoiceToExpire invoiceExpiry
1,355✔
1053

1,355✔
1054
        switch res := resolution.(type) {
1,355✔
1055
        case *HtlcFailResolution:
30✔
1056
                // Inspect latest htlc state on the invoice. If it is found,
30✔
1057
                // we will update the accept height as it was recorded in the
30✔
1058
                // invoice database (which occurs in the case where the htlc
30✔
1059
                // reached the database in a previous call). If the htlc was
30✔
1060
                // not found on the invoice, it was immediately failed so we
30✔
1061
                // send the failure resolution as is, which has the current
30✔
1062
                // height set as the accept height.
30✔
1063
                invoiceHtlc, ok := invoice.Htlcs[ctx.circuitKey]
30✔
1064
                if ok {
37✔
1065
                        res.AcceptHeight = int32(invoiceHtlc.AcceptHeight)
7✔
1066
                }
7✔
1067

1068
                ctx.log(fmt.Sprintf("failure resolution result "+
30✔
1069
                        "outcome: %v, at accept height: %v",
30✔
1070
                        res.Outcome, res.AcceptHeight))
30✔
1071

30✔
1072
                // Some failures apply to the entire HTLC set. Break here if
30✔
1073
                // this isn't one of them.
30✔
1074
                if !res.Outcome.IsSetFailure() {
54✔
1075
                        break
24✔
1076
                }
1077

1078
                // Also cancel any HTLCs in the HTLC set that are also in the
1079
                // canceled state with the same failure result.
1080
                setID := ctx.setID()
6✔
1081
                canceledHtlcSet := invoice.HTLCSet(setID, HtlcStateCanceled)
6✔
1082
                for key, htlc := range canceledHtlcSet {
12✔
1083
                        htlcFailResolution := NewFailResolution(
6✔
1084
                                key, int32(htlc.AcceptHeight), res.Outcome,
6✔
1085
                        )
6✔
1086

6✔
1087
                        i.notifyHodlSubscribers(htlcFailResolution)
6✔
1088
                }
6✔
1089

1090
        // If the htlc was settled, we will settle any previously accepted
1091
        // htlcs and notify our peer to settle them.
1092
        case *HtlcSettleResolution:
477✔
1093
                ctx.log(fmt.Sprintf("settle resolution result "+
477✔
1094
                        "outcome: %v, at accept height: %v",
477✔
1095
                        res.Outcome, res.AcceptHeight))
477✔
1096

477✔
1097
                // Also settle any previously accepted htlcs. If a htlc is
477✔
1098
                // marked as settled, we should follow now and settle the htlc
477✔
1099
                // with our peer.
477✔
1100
                setID := ctx.setID()
477✔
1101
                settledHtlcSet := invoice.HTLCSet(setID, HtlcStateSettled)
477✔
1102
                for key, htlc := range settledHtlcSet {
1,266✔
1103
                        preimage := res.Preimage
789✔
1104
                        if htlc.AMP != nil && htlc.AMP.Preimage != nil {
805✔
1105
                                preimage = *htlc.AMP.Preimage
16✔
1106
                        }
16✔
1107

1108
                        // Notify subscribers that the htlcs should be settled
1109
                        // with our peer. Note that the outcome of the
1110
                        // resolution is set based on the outcome of the single
1111
                        // htlc that we just settled, so may not be accurate
1112
                        // for all htlcs.
1113
                        htlcSettleResolution := NewSettleResolution(
789✔
1114
                                preimage, key,
789✔
1115
                                int32(htlc.AcceptHeight), res.Outcome,
789✔
1116
                        )
789✔
1117

789✔
1118
                        // Notify subscribers that the htlc should be settled
789✔
1119
                        // with our peer.
789✔
1120
                        i.notifyHodlSubscribers(htlcSettleResolution)
789✔
1121
                }
1122

1123
                // If concurrent payments were attempted to this invoice before
1124
                // the current one was ultimately settled, cancel back any of
1125
                // the HTLCs immediately. As a result of the settle, the HTLCs
1126
                // in other HTLC sets are automatically converted to a canceled
1127
                // state when updating the invoice.
1128
                //
1129
                // TODO(roasbeef): can remove now??
1130
                canceledHtlcSet := invoice.HTLCSetCompliment(
477✔
1131
                        setID, HtlcStateCanceled,
477✔
1132
                )
477✔
1133
                for key, htlc := range canceledHtlcSet {
477✔
1134
                        htlcFailResolution := NewFailResolution(
×
1135
                                key, int32(htlc.AcceptHeight),
×
1136
                                ResultInvoiceAlreadySettled,
×
1137
                        )
×
1138

×
1139
                        i.notifyHodlSubscribers(htlcFailResolution)
×
1140
                }
×
1141

1142
        // If we accepted the htlc, subscribe to the hodl invoice and return
1143
        // an accept resolution with the htlc's accept time on it.
1144
        case *htlcAcceptResolution:
856✔
1145
                invoiceHtlc, ok := invoice.Htlcs[ctx.circuitKey]
856✔
1146
                if !ok {
856✔
1147
                        return nil, nil, fmt.Errorf("accepted htlc: %v not"+
×
1148
                                " present on invoice: %x", ctx.circuitKey,
×
1149
                                ctx.hash[:])
×
1150
                }
×
1151

1152
                // Determine accepted height of this htlc. If the htlc reached
1153
                // the invoice database (possibly in a previous call to the
1154
                // invoice registry), we'll take the original accepted height
1155
                // as it was recorded in the database.
1156
                acceptHeight := int32(invoiceHtlc.AcceptHeight)
856✔
1157

856✔
1158
                ctx.log(fmt.Sprintf("accept resolution result "+
856✔
1159
                        "outcome: %v, at accept height: %v",
856✔
1160
                        res.outcome, acceptHeight))
856✔
1161

856✔
1162
                // Auto-release the htlc if the invoice is still open. It can
856✔
1163
                // only happen for mpp payments that there are htlcs in state
856✔
1164
                // Accepted while the invoice is Open.
856✔
1165
                if invoice.State == ContractOpen {
1,190✔
1166
                        res.acceptTime = invoiceHtlc.AcceptTime
334✔
1167
                        res.autoRelease = true
334✔
1168
                }
334✔
1169

1170
                // If we have fully accepted the set of htlcs for this invoice,
1171
                // we can now add it to our invoice expiry watcher. We do not
1172
                // add invoices before they are fully accepted, because it is
1173
                // possible that we MppTimeout the htlcs, and then our relevant
1174
                // expiry height could change.
1175
                if res.outcome == resultAccepted {
1,375✔
1176
                        invoiceToExpire = makeInvoiceExpiry(ctx.hash, invoice)
519✔
1177
                }
519✔
1178

1179
                i.hodlSubscribe(hodlChan, ctx.circuitKey)
856✔
1180

1181
        default:
×
1182
                panic("unknown action")
×
1183
        }
1184

1185
        // Now that the links have been notified of any state changes to their
1186
        // HTLCs, we'll go ahead and notify any clients wiaiting on the invoice
1187
        // state changes.
1188
        if updateSubscribers {
2,344✔
1189
                // We'll add a setID onto the notification, but only if this is
989✔
1190
                // an AMP invoice being settled.
989✔
1191
                var setID *[32]byte
989✔
1192
                if _, ok := resolution.(*HtlcSettleResolution); ok {
1,457✔
1193
                        setID = ctx.setID()
468✔
1194
                }
468✔
1195

1196
                i.notifyClients(ctx.hash, invoice, setID)
989✔
1197
        }
1198

1199
        return resolution, invoiceToExpire, nil
1,355✔
1200
}
1201

1202
// SettleHodlInvoice sets the preimage of a hodl invoice.
1203
func (i *InvoiceRegistry) SettleHodlInvoice(ctx context.Context,
1204
        preimage lntypes.Preimage) error {
506✔
1205

506✔
1206
        i.Lock()
506✔
1207
        defer i.Unlock()
506✔
1208

506✔
1209
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
1,012✔
1210
                switch invoice.State {
506✔
1211
                case ContractOpen:
×
1212
                        return nil, ErrInvoiceStillOpen
×
1213

1214
                case ContractCanceled:
×
1215
                        return nil, ErrInvoiceAlreadyCanceled
×
1216

1217
                case ContractSettled:
3✔
1218
                        return nil, ErrInvoiceAlreadySettled
3✔
1219
                }
1220

1221
                return &InvoiceUpdateDesc{
503✔
1222
                        UpdateType: SettleHodlInvoiceUpdate,
503✔
1223
                        State: &InvoiceStateUpdateDesc{
503✔
1224
                                NewState: ContractSettled,
503✔
1225
                                Preimage: &preimage,
503✔
1226
                        },
503✔
1227
                }, nil
503✔
1228
        }
1229

1230
        hash := preimage.Hash()
506✔
1231
        invoiceRef := InvoiceRefByHash(hash)
506✔
1232
        invoice, err := i.idb.UpdateInvoice(ctx, invoiceRef, nil, updateInvoice)
506✔
1233
        if err != nil {
509✔
1234
                log.Errorf("SettleHodlInvoice with preimage %v: %v",
3✔
1235
                        preimage, err)
3✔
1236

3✔
1237
                return err
3✔
1238
        }
3✔
1239

1240
        log.Debugf("Invoice%v: settled with preimage %v", invoiceRef,
503✔
1241
                invoice.Terms.PaymentPreimage)
503✔
1242

503✔
1243
        // In the callback, we marked the invoice as settled. UpdateInvoice will
503✔
1244
        // have seen this and should have moved all htlcs that were accepted to
503✔
1245
        // the settled state. In the loop below, we go through all of these and
503✔
1246
        // notify links and resolvers that are waiting for resolution. Any htlcs
503✔
1247
        // that were already settled before, will be notified again. This isn't
503✔
1248
        // necessary but doesn't hurt either.
503✔
1249
        for key, htlc := range invoice.Htlcs {
1,009✔
1250
                if htlc.State != HtlcStateSettled {
506✔
1251
                        continue
×
1252
                }
1253

1254
                resolution := NewSettleResolution(
506✔
1255
                        preimage, key, int32(htlc.AcceptHeight), ResultSettled,
506✔
1256
                )
506✔
1257

506✔
1258
                i.notifyHodlSubscribers(resolution)
506✔
1259
        }
1260
        i.notifyClients(hash, invoice, nil)
503✔
1261

503✔
1262
        return nil
503✔
1263
}
1264

1265
// CancelInvoice attempts to cancel the invoice corresponding to the passed
1266
// payment hash.
1267
func (i *InvoiceRegistry) CancelInvoice(ctx context.Context,
1268
        payHash lntypes.Hash) error {
33✔
1269

33✔
1270
        return i.cancelInvoiceImpl(ctx, payHash, true)
33✔
1271
}
33✔
1272

1273
// shouldCancel examines the state of an invoice and whether we want to
1274
// cancel already accepted invoices, taking our force cancel boolean into
1275
// account. This is pulled out into its own function so that tests that mock
1276
// cancelInvoiceImpl can reuse this logic.
1277
func shouldCancel(state ContractState, cancelAccepted bool) bool {
98✔
1278
        if state != ContractAccepted {
168✔
1279
                return true
70✔
1280
        }
70✔
1281

1282
        // If the invoice is accepted, we should only cancel if we want to
1283
        // force cancellation of accepted invoices.
1284
        return cancelAccepted
32✔
1285
}
1286

1287
// cancelInvoice attempts to cancel the invoice corresponding to the passed
1288
// payment hash. Accepted invoices will only be canceled if explicitly
1289
// requested to do so. It notifies subscribing links and resolvers that
1290
// the associated htlcs were canceled if they change state.
1291
func (i *InvoiceRegistry) cancelInvoiceImpl(ctx context.Context,
1292
        payHash lntypes.Hash, cancelAccepted bool) error {
107✔
1293

107✔
1294
        i.Lock()
107✔
1295
        defer i.Unlock()
107✔
1296

107✔
1297
        ref := InvoiceRefByHash(payHash)
107✔
1298
        log.Debugf("Invoice%v: canceling invoice", ref)
107✔
1299

107✔
1300
        updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
205✔
1301
                if !shouldCancel(invoice.State, cancelAccepted) {
110✔
1302
                        return nil, nil
12✔
1303
                }
12✔
1304

1305
                // Move invoice to the canceled state. Rely on validation in
1306
                // channeldb to return an error if the invoice is already
1307
                // settled or canceled.
1308
                return &InvoiceUpdateDesc{
86✔
1309
                        UpdateType: CancelInvoiceUpdate,
86✔
1310
                        State: &InvoiceStateUpdateDesc{
86✔
1311
                                NewState: ContractCanceled,
86✔
1312
                        },
86✔
1313
                }, nil
86✔
1314
        }
1315

1316
        invoiceRef := InvoiceRefByHash(payHash)
107✔
1317
        invoice, err := i.idb.UpdateInvoice(ctx, invoiceRef, nil, updateInvoice)
107✔
1318

107✔
1319
        // Implement idempotency by returning success if the invoice was already
107✔
1320
        // canceled.
107✔
1321
        if errors.Is(err, ErrInvoiceAlreadyCanceled) {
110✔
1322
                log.Debugf("Invoice%v: already canceled", ref)
3✔
1323
                return nil
3✔
1324
        }
3✔
1325
        if err != nil {
128✔
1326
                return err
24✔
1327
        }
24✔
1328

1329
        // Return without cancellation if the invoice state is ContractAccepted.
1330
        if invoice.State == ContractAccepted {
96✔
1331
                log.Debugf("Invoice%v: remains accepted as cancel wasn't"+
12✔
1332
                        "explicitly requested.", ref)
12✔
1333
                return nil
12✔
1334
        }
12✔
1335

1336
        log.Debugf("Invoice%v: canceled", ref)
72✔
1337

72✔
1338
        // In the callback, some htlcs may have been moved to the canceled
72✔
1339
        // state. We now go through all of these and notify links and resolvers
72✔
1340
        // that are waiting for resolution. Any htlcs that were already canceled
72✔
1341
        // before, will be notified again. This isn't necessary but doesn't hurt
72✔
1342
        // either.
72✔
1343
        for key, htlc := range invoice.Htlcs {
101✔
1344
                if htlc.State != HtlcStateCanceled {
29✔
1345
                        continue
×
1346
                }
1347

1348
                i.notifyHodlSubscribers(
29✔
1349
                        NewFailResolution(
29✔
1350
                                key, int32(htlc.AcceptHeight), ResultCanceled,
29✔
1351
                        ),
29✔
1352
                )
29✔
1353
        }
1354
        i.notifyClients(payHash, invoice, nil)
72✔
1355

72✔
1356
        // Attempt to also delete the invoice if requested through the registry
72✔
1357
        // config.
72✔
1358
        if i.cfg.GcCanceledInvoicesOnTheFly {
75✔
1359
                // Assemble the delete reference and attempt to delete through
3✔
1360
                // the invocice from the DB.
3✔
1361
                deleteRef := InvoiceDeleteRef{
3✔
1362
                        PayHash:     payHash,
3✔
1363
                        AddIndex:    invoice.AddIndex,
3✔
1364
                        SettleIndex: invoice.SettleIndex,
3✔
1365
                }
3✔
1366
                if invoice.Terms.PaymentAddr != BlankPayAddr {
3✔
1367
                        deleteRef.PayAddr = &invoice.Terms.PaymentAddr
×
1368
                }
×
1369

1370
                err = i.idb.DeleteInvoice(ctx, []InvoiceDeleteRef{deleteRef})
3✔
1371
                // If by any chance deletion failed, then log it instead of
3✔
1372
                // returning the error, as the invoice itself has already been
3✔
1373
                // canceled.
3✔
1374
                if err != nil {
3✔
1375
                        log.Warnf("Invoice %v could not be deleted: %v", ref,
×
1376
                                err)
×
1377
                }
×
1378
        }
1379

1380
        return nil
72✔
1381
}
1382

1383
// notifyClients notifies all currently registered invoice notification clients
1384
// of a newly added/settled invoice.
1385
func (i *InvoiceRegistry) notifyClients(hash lntypes.Hash,
1386
        invoice *Invoice, setID *[32]byte) {
2,693✔
1387

2,693✔
1388
        event := &invoiceEvent{
2,693✔
1389
                invoice: invoice,
2,693✔
1390
                hash:    hash,
2,693✔
1391
                setID:   setID,
2,693✔
1392
        }
2,693✔
1393

2,693✔
1394
        select {
2,693✔
1395
        case i.invoiceEvents <- event:
2,693✔
1396
        case <-i.quit:
×
1397
        }
1398
}
1399

1400
// invoiceSubscriptionKit defines that are common to both all invoice
1401
// subscribers and single invoice subscribers.
1402
type invoiceSubscriptionKit struct {
1403
        id uint32 // nolint:structcheck
1404

1405
        // quit is a chan mouted to InvoiceRegistry that signals a shutdown.
1406
        quit chan struct{}
1407

1408
        ntfnQueue *queue.ConcurrentQueue
1409

1410
        canceled   uint32 // To be used atomically.
1411
        cancelChan chan struct{}
1412

1413
        // backlogDelivered is closed when the backlog events have been
1414
        // delivered.
1415
        backlogDelivered chan struct{}
1416
}
1417

1418
// InvoiceSubscription represents an intent to receive updates for newly added
1419
// or settled invoices. For each newly added invoice, a copy of the invoice
1420
// will be sent over the NewInvoices channel. Similarly, for each newly settled
1421
// invoice, a copy of the invoice will be sent over the SettledInvoices
1422
// channel.
1423
type InvoiceSubscription struct {
1424
        invoiceSubscriptionKit
1425

1426
        // NewInvoices is a channel that we'll use to send all newly created
1427
        // invoices with an invoice index greater than the specified
1428
        // StartingInvoiceIndex field.
1429
        NewInvoices chan *Invoice
1430

1431
        // SettledInvoices is a channel that we'll use to send all settled
1432
        // invoices with an invoices index greater than the specified
1433
        // StartingInvoiceIndex field.
1434
        SettledInvoices chan *Invoice
1435

1436
        // addIndex is the highest add index the caller knows of. We'll use
1437
        // this information to send out an event backlog to the notifications
1438
        // subscriber. Any new add events with an index greater than this will
1439
        // be dispatched before any new notifications are sent out.
1440
        addIndex uint64
1441

1442
        // settleIndex is the highest settle index the caller knows of. We'll
1443
        // use this information to send out an event backlog to the
1444
        // notifications subscriber. Any new settle events with an index
1445
        // greater than this will be dispatched before any new notifications
1446
        // are sent out.
1447
        settleIndex uint64
1448
}
1449

1450
// SingleInvoiceSubscription represents an intent to receive updates for a
1451
// specific invoice.
1452
type SingleInvoiceSubscription struct {
1453
        invoiceSubscriptionKit
1454

1455
        invoiceRef InvoiceRef
1456

1457
        // Updates is a channel that we'll use to send all invoice events for
1458
        // the invoice that is subscribed to.
1459
        Updates chan *Invoice
1460
}
1461

1462
// PayHash returns the optional payment hash of the target invoice.
1463
//
1464
// TODO(positiveblue): This method is only supposed to be used in tests. It will
1465
// be deleted as soon as invoiceregistery_test is in the same module.
1466
func (s *SingleInvoiceSubscription) PayHash() *lntypes.Hash {
18✔
1467
        return s.invoiceRef.PayHash()
18✔
1468
}
18✔
1469

1470
// Cancel unregisters the InvoiceSubscription, freeing any previously allocated
1471
// resources.
1472
func (i *invoiceSubscriptionKit) Cancel() {
67✔
1473
        if !atomic.CompareAndSwapUint32(&i.canceled, 0, 1) {
67✔
1474
                return
×
1475
        }
×
1476

1477
        i.ntfnQueue.Stop()
67✔
1478
        close(i.cancelChan)
67✔
1479
}
1480

1481
func (i *invoiceSubscriptionKit) notify(event *invoiceEvent) error {
106✔
1482
        select {
106✔
1483
        case i.ntfnQueue.ChanIn() <- event:
106✔
1484

1485
        case <-i.cancelChan:
×
1486
                // This can only be triggered by delivery of non-backlog
×
1487
                // events.
×
1488
                return ErrShuttingDown
×
1489
        case <-i.quit:
×
1490
                return ErrShuttingDown
×
1491
        }
1492

1493
        return nil
106✔
1494
}
1495

1496
// SubscribeNotifications returns an InvoiceSubscription which allows the
1497
// caller to receive async notifications when any invoices are settled or
1498
// added. The invoiceIndex parameter is a streaming "checkpoint". We'll start
1499
// by first sending out all new events with an invoice index _greater_ than
1500
// this value. Afterwards, we'll send out real-time notifications.
1501
func (i *InvoiceRegistry) SubscribeNotifications(ctx context.Context,
1502
        addIndex, settleIndex uint64) (*InvoiceSubscription, error) {
49✔
1503

49✔
1504
        client := &InvoiceSubscription{
49✔
1505
                NewInvoices:     make(chan *Invoice),
49✔
1506
                SettledInvoices: make(chan *Invoice),
49✔
1507
                addIndex:        addIndex,
49✔
1508
                settleIndex:     settleIndex,
49✔
1509
                invoiceSubscriptionKit: invoiceSubscriptionKit{
49✔
1510
                        quit:             i.quit,
49✔
1511
                        ntfnQueue:        queue.NewConcurrentQueue(20),
49✔
1512
                        cancelChan:       make(chan struct{}),
49✔
1513
                        backlogDelivered: make(chan struct{}),
49✔
1514
                },
49✔
1515
        }
49✔
1516
        client.ntfnQueue.Start()
49✔
1517

49✔
1518
        // This notifies other goroutines that the backlog phase is over.
49✔
1519
        defer close(client.backlogDelivered)
49✔
1520

49✔
1521
        // Always increment by 1 first, and our client ID will start with 1,
49✔
1522
        // not 0.
49✔
1523
        client.id = atomic.AddUint32(&i.nextClientID, 1)
49✔
1524

49✔
1525
        // Before we register this new invoice subscription, we'll launch a new
49✔
1526
        // goroutine that will proxy all notifications appended to the end of
49✔
1527
        // the concurrent queue to the two client-side channels the caller will
49✔
1528
        // feed off of.
49✔
1529
        i.wg.Add(1)
49✔
1530
        go func() {
98✔
1531
                defer i.wg.Done()
49✔
1532
                defer i.deleteClient(client.id)
49✔
1533

49✔
1534
                for {
164✔
1535
                        select {
115✔
1536
                        // A new invoice event has been sent by the
1537
                        // invoiceRegistry! We'll figure out if this is an add
1538
                        // event or a settle event, then dispatch the event to
1539
                        // the client.
1540
                        case ntfn := <-client.ntfnQueue.ChanOut():
70✔
1541
                                invoiceEvent := ntfn.(*invoiceEvent)
70✔
1542

70✔
1543
                                var targetChan chan *Invoice
70✔
1544
                                state := invoiceEvent.invoice.State
70✔
1545
                                switch {
70✔
1546
                                // AMP invoices never move to settled, but will
1547
                                // be sent with a set ID if an HTLC set is
1548
                                // being settled.
1549
                                case state == ContractOpen &&
1550
                                        invoiceEvent.setID != nil:
10✔
1551
                                        fallthrough
10✔
1552

1553
                                case state == ContractSettled:
28✔
1554
                                        targetChan = client.SettledInvoices
28✔
1555

1556
                                case state == ContractOpen:
46✔
1557
                                        targetChan = client.NewInvoices
46✔
1558

1559
                                default:
×
1560
                                        log.Errorf("unknown invoice state: %v",
×
1561
                                                state)
×
1562

×
1563
                                        continue
×
1564
                                }
1565

1566
                                select {
70✔
1567
                                case targetChan <- invoiceEvent.invoice:
70✔
1568

1569
                                case <-client.cancelChan:
×
1570
                                        return
×
1571

1572
                                case <-i.quit:
×
1573
                                        return
×
1574
                                }
1575

1576
                        case <-client.cancelChan:
48✔
1577
                                return
48✔
1578

1579
                        case <-i.quit:
1✔
1580
                                return
1✔
1581
                        }
1582
                }
1583
        }()
1584

1585
        i.notificationClientMux.Lock()
49✔
1586
        i.notificationClients[client.id] = client
49✔
1587
        i.notificationClientMux.Unlock()
49✔
1588

49✔
1589
        // Query the database to see if based on the provided addIndex and
49✔
1590
        // settledIndex we need to deliver any backlog notifications.
49✔
1591
        err := i.deliverBacklogEvents(ctx, client)
49✔
1592
        if err != nil {
49✔
1593
                return nil, err
×
1594
        }
×
1595

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

49✔
1598
        return client, nil
49✔
1599
}
1600

1601
// SubscribeSingleInvoice returns an SingleInvoiceSubscription which allows the
1602
// caller to receive async notifications for a specific invoice.
1603
func (i *InvoiceRegistry) SubscribeSingleInvoice(ctx context.Context,
1604
        hash lntypes.Hash) (*SingleInvoiceSubscription, error) {
22✔
1605

22✔
1606
        client := &SingleInvoiceSubscription{
22✔
1607
                Updates: make(chan *Invoice),
22✔
1608
                invoiceSubscriptionKit: invoiceSubscriptionKit{
22✔
1609
                        quit:             i.quit,
22✔
1610
                        ntfnQueue:        queue.NewConcurrentQueue(20),
22✔
1611
                        cancelChan:       make(chan struct{}),
22✔
1612
                        backlogDelivered: make(chan struct{}),
22✔
1613
                },
22✔
1614
                invoiceRef: InvoiceRefByHash(hash),
22✔
1615
        }
22✔
1616
        client.ntfnQueue.Start()
22✔
1617

22✔
1618
        // This notifies other goroutines that the backlog phase is done.
22✔
1619
        defer close(client.backlogDelivered)
22✔
1620

22✔
1621
        // Always increment by 1 first, and our client ID will start with 1,
22✔
1622
        // not 0.
22✔
1623
        client.id = atomic.AddUint32(&i.nextClientID, 1)
22✔
1624

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

22✔
1634
                for {
80✔
1635
                        select {
58✔
1636
                        // A new invoice event has been sent by the
1637
                        // invoiceRegistry. We will dispatch the event to the
1638
                        // client.
1639
                        case ntfn := <-client.ntfnQueue.ChanOut():
40✔
1640
                                invoiceEvent := ntfn.(*invoiceEvent)
40✔
1641

40✔
1642
                                select {
40✔
1643
                                case client.Updates <- invoiceEvent.invoice:
40✔
1644

1645
                                case <-client.cancelChan:
×
1646
                                        return
×
1647

1648
                                case <-i.quit:
×
1649
                                        return
×
1650
                                }
1651

1652
                        case <-client.cancelChan:
22✔
1653
                                return
22✔
1654

1655
                        case <-i.quit:
×
1656
                                return
×
1657
                        }
1658
                }
1659
        }()
1660

1661
        i.notificationClientMux.Lock()
22✔
1662
        i.singleNotificationClients[client.id] = client
22✔
1663
        i.notificationClientMux.Unlock()
22✔
1664

22✔
1665
        err := i.deliverSingleBacklogEvents(ctx, client)
22✔
1666
        if err != nil {
22✔
1667
                return nil, err
×
1668
        }
×
1669

1670
        log.Infof("New single invoice subscription client: id=%v, ref=%v",
22✔
1671
                client.id, client.invoiceRef)
22✔
1672

22✔
1673
        return client, nil
22✔
1674
}
1675

1676
// notifyHodlSubscribers sends out the htlc resolution to all current
1677
// subscribers.
1678
func (i *InvoiceRegistry) notifyHodlSubscribers(htlcResolution HtlcResolution) {
1,328✔
1679
        i.hodlSubscriptionsMux.Lock()
1,328✔
1680
        defer i.hodlSubscriptionsMux.Unlock()
1,328✔
1681

1,328✔
1682
        subscribers, ok := i.hodlSubscriptions[htlcResolution.CircuitKey()]
1,328✔
1683
        if !ok {
1,811✔
1684
                return
483✔
1685
        }
483✔
1686

1687
        // Notify all interested subscribers and remove subscription from both
1688
        // maps. The subscription can be removed as there only ever will be a
1689
        // single resolution for each hash.
1690
        for subscriber := range subscribers {
1,698✔
1691
                select {
849✔
1692
                case subscriber <- htlcResolution:
849✔
1693
                case <-i.quit:
×
1694
                        return
×
1695
                }
1696

1697
                delete(
849✔
1698
                        i.hodlReverseSubscriptions[subscriber],
849✔
1699
                        htlcResolution.CircuitKey(),
849✔
1700
                )
849✔
1701
        }
1702

1703
        delete(i.hodlSubscriptions, htlcResolution.CircuitKey())
849✔
1704
}
1705

1706
// hodlSubscribe adds a new invoice subscription.
1707
func (i *InvoiceRegistry) hodlSubscribe(subscriber chan<- interface{},
1708
        circuitKey CircuitKey) {
856✔
1709

856✔
1710
        i.hodlSubscriptionsMux.Lock()
856✔
1711
        defer i.hodlSubscriptionsMux.Unlock()
856✔
1712

856✔
1713
        log.Debugf("Hodl subscribe for %v", circuitKey)
856✔
1714

856✔
1715
        subscriptions, ok := i.hodlSubscriptions[circuitKey]
856✔
1716
        if !ok {
1,705✔
1717
                subscriptions = make(map[chan<- interface{}]struct{})
849✔
1718
                i.hodlSubscriptions[circuitKey] = subscriptions
849✔
1719
        }
849✔
1720
        subscriptions[subscriber] = struct{}{}
856✔
1721

856✔
1722
        reverseSubscriptions, ok := i.hodlReverseSubscriptions[subscriber]
856✔
1723
        if !ok {
1,217✔
1724
                reverseSubscriptions = make(map[CircuitKey]struct{})
361✔
1725
                i.hodlReverseSubscriptions[subscriber] = reverseSubscriptions
361✔
1726
        }
361✔
1727
        reverseSubscriptions[circuitKey] = struct{}{}
856✔
1728
}
1729

1730
// HodlUnsubscribeAll cancels the subscription.
1731
func (i *InvoiceRegistry) HodlUnsubscribeAll(subscriber chan<- interface{}) {
204✔
1732
        i.hodlSubscriptionsMux.Lock()
204✔
1733
        defer i.hodlSubscriptionsMux.Unlock()
204✔
1734

204✔
1735
        hashes := i.hodlReverseSubscriptions[subscriber]
204✔
1736
        for hash := range hashes {
209✔
1737
                delete(i.hodlSubscriptions[hash], subscriber)
5✔
1738
        }
5✔
1739

1740
        delete(i.hodlReverseSubscriptions, subscriber)
204✔
1741
}
1742

1743
// copySingleClients copies i.SingleInvoiceSubscription inside a lock. This is
1744
// useful when we need to iterate the map to send notifications.
1745
func (i *InvoiceRegistry) copySingleClients() map[uint32]*SingleInvoiceSubscription { //nolint:lll
2,693✔
1746
        i.notificationClientMux.RLock()
2,693✔
1747
        defer i.notificationClientMux.RUnlock()
2,693✔
1748

2,693✔
1749
        clients := make(map[uint32]*SingleInvoiceSubscription)
2,693✔
1750
        for k, v := range i.singleNotificationClients {
2,733✔
1751
                clients[k] = v
40✔
1752
        }
40✔
1753
        return clients
2,693✔
1754
}
1755

1756
// copyClients copies i.notificationClients inside a lock. This is useful when
1757
// we need to iterate the map to send notifications.
1758
func (i *InvoiceRegistry) copyClients() map[uint32]*InvoiceSubscription {
2,104✔
1759
        i.notificationClientMux.RLock()
2,104✔
1760
        defer i.notificationClientMux.RUnlock()
2,104✔
1761

2,104✔
1762
        clients := make(map[uint32]*InvoiceSubscription)
2,104✔
1763
        for k, v := range i.notificationClients {
2,174✔
1764
                clients[k] = v
70✔
1765
        }
70✔
1766
        return clients
2,104✔
1767
}
1768

1769
// deleteClient removes a client by its ID inside a lock. Noop if the client is
1770
// not found.
1771
func (i *InvoiceRegistry) deleteClient(clientID uint32) {
67✔
1772
        i.notificationClientMux.Lock()
67✔
1773
        defer i.notificationClientMux.Unlock()
67✔
1774

67✔
1775
        log.Infof("Cancelling invoice subscription for client=%v", clientID)
67✔
1776
        delete(i.notificationClients, clientID)
67✔
1777
        delete(i.singleNotificationClients, clientID)
67✔
1778
}
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