diff --git a/internal/lnurlcash/jobs.go b/internal/lnurlcash/jobs.go new file mode 100644 index 00000000..992cc85c --- /dev/null +++ b/internal/lnurlcash/jobs.go @@ -0,0 +1,402 @@ +package lnurlcash + +import ( + "context" + "errors" + "sync" + "time" + + lnurlcash "github.com/lnurlcash/lnurlcash-go" + log "github.com/sirupsen/logrus" +) + +// Notifier is how the jobs reach Telegram. Every method must be safe to call +// from a background goroutine and must never block on user input. +type Notifier interface { + // NoteClaimed tells a single note's creator that it was redeemed. + NoteClaimed(n *Note) + // BatchDigest tells a batch creator which notes were claimed since the last digest. + BatchDigest(b *Batch, claimed []*Note) + // NoteReclaimed tells the creator a reclaim settled. + NoteReclaimed(n *Note) + // RedeemSettled tells the redeemer the sats arrived. + RedeemSettled(r *Redeem) + // GroupNoteState edits a note's group post ("claimed", "withdrawn"). + GroupNoteState(n *Note) + // Alert reaches the admin. + Alert(msg string) +} + +// Jobs runs the background work: claim watching, pending recovery, mint +// health and auto reclaim. +type Jobs struct { + svc *Service + notifier Notifier + // perRun caps how many notes one watcher run probes. + perRun int + + watchMu sync.Mutex + recoverMu sync.Mutex +} + +// NewJobs wires the jobs. notifier may be nil (then nothing is sent). +func NewJobs(svc *Service, notifier Notifier) *Jobs { + if notifier == nil { + notifier = noopNotifier{} + } + return &Jobs{svc: svc, notifier: notifier, perRun: 200} +} + +type noopNotifier struct{} + +func (noopNotifier) NoteClaimed(*Note) {} +func (noopNotifier) BatchDigest(*Batch, []*Note) {} +func (noopNotifier) NoteReclaimed(*Note) {} +func (noopNotifier) RedeemSettled(*Redeem) {} +func (noopNotifier) GroupNoteState(*Note) {} +func (noopNotifier) Alert(string) {} + +// Start launches every job until ctx ends. +func (j *Jobs) Start(ctx context.Context) { + cfg := j.svc.cfg + go j.svc.mints.RunHealth(ctx, 5*time.Minute) + go j.loop(ctx, time.Minute, j.RecoverOnce) + go j.loop(ctx, cfg.StatusPollInterval, j.WatchOnce) + if cfg.AutoReclaimDays > 0 { + go j.loop(ctx, 24*time.Hour, j.AutoReclaimOnce) + } + log.Infof("[lnurlcash] jobs started (poll %s, auto reclaim %d days)", cfg.StatusPollInterval, cfg.AutoReclaimDays) +} + +func (j *Jobs) loop(ctx context.Context, every time.Duration, run func(context.Context)) { + // first run shortly after start, once the mint health check had a chance + select { + case <-ctx.Done(): + return + case <-time.After(5 * time.Second): + } + run(ctx) + t := time.NewTicker(every) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + run(ctx) + } + } +} + +// WatchOnce probes live user notes and reports the ones that were claimed. +func (j *Jobs) WatchOnce(ctx context.Context) { + if !j.watchMu.TryLock() { + return + } + defer j.watchMu.Unlock() + notes, err := j.svc.store.NotesByState([]string{NoteLive}, []string{KindUser}, j.perRun) + if err != nil { + log.Errorf("[lnurlcash] watcher: %v", err) + return + } + claimedInBatch := map[string][]*Note{} + for _, n := range notes { + if ctx.Err() != nil { + return + } + state, _, err := j.svc.Status(ctx, n) + if err != nil && !errors.Is(err, lnurlcash.ErrNotePending) { + continue + } + if state != NoteClaimed { + continue + } + j.notifier.GroupNoteState(n) + if n.BatchID != nil { + if b, err := j.svc.store.Batch(*n.BatchID); err == nil && b.Count > 1 { + claimedInBatch[b.ID] = append(claimedInBatch[b.ID], n) + continue + } + } + j.notifier.NoteClaimed(n) + } + for id, claimed := range claimedInBatch { + b, err := j.svc.store.Batch(id) + if err != nil { + continue + } + if time.Since(b.LastDigestAt) < time.Hour { + continue // the next run will fold these into the next digest via the DB state + } + j.notifier.BatchDigest(b, claimed) + _ = j.svc.store.UpdateBatch(b.ID, map[string]interface{}{"last_digest_at": time.Now()}) + } +} + +// RecoverOnce finishes or rolls back every row in a non-final state. +func (j *Jobs) RecoverOnce(ctx context.Context) { + if !j.recoverMu.TryLock() { + return + } + defer j.recoverMu.Unlock() + j.recoverBatches(ctx) + j.recoverReclaims(ctx) + j.recoverRedeems(ctx) +} + +// recoverBatches resumes batches whose funding or carving stopped midway. +func (j *Jobs) recoverBatches(ctx context.Context) { + batches, err := j.svc.store.BatchesByState([]string{BatchPendingInvoice, BatchPendingSettle, BatchCarving, BatchUnknown}) + if err != nil { + log.Errorf("[lnurlcash] recovery: %v", err) + return + } + for _, b := range batches { + if ctx.Err() != nil { + return + } + if time.Since(b.UpdatedAt) < 30*time.Second { + continue // a handler may still be working on it + } + j.recoverBatch(ctx, b) + } +} + +func (j *Jobs) recoverBatch(ctx context.Context, b *Batch) { + s := j.svc + unlock := lockNote(b.ID) + defer unlock() + notes, err := s.store.NotesInBatch(b.ID) + if err != nil { + return + } + if _, ok := s.mints.Get(b.MintID); !ok { + return + } + // rebuild the units: one funding note and the user/dust pairs that follow it + var units []*unit + byIndex := map[int][2]*Note{} + for _, n := range notes { + switch n.Kind { + case KindFunding: + units = append(units, &unit{funding: n}) + case KindUser: + p := byIndex[n.Index] + p[0] = n + byIndex[n.Index] = p + case KindDust: + p := byIndex[n.Index] + p[1] = n + byIndex[n.Index] = p + } + } + if len(units) == 0 { + return + } + perUnit := b.Count / len(units) + idx := 1 + for _, un := range units { + for i := 0; i < perUnit; i++ { + p := byIndex[idx] + idx++ + if p[0] == nil || p[1] == nil { + continue + } + un.notes = append(un.notes, p[0]) + un.dust = append(un.dust, p[1]) + } + } + for _, un := range units { + f := un.funding + switch f.State { + case NotePendingInvoice: + // no invoice was ever requested: nothing was paid + s.failUnit(b, un, "recovery: no invoice requested") + continue + case NotePendingSettle: + // was the mint invoice paid? LNbits knows; the mint knows + if f.InvoiceHash != "" { + paid, pending, err := s.ledger.PaymentSucceeded(ctx, b.UserName, f.InvoiceHash) + if err == nil && !paid && !pending { + s.failUnit(b, un, "recovery: mint invoice payment failed") + continue + } + } + found, err := s.waitFunding(ctx, f, 0) + if err != nil || !found { + continue + } + case NoteFailed: + continue + } + // any note carved in state unknown: ask the mint whether its hash exists + for i, n := range un.notes { + if n.State == NoteUnknown { + if _, err := s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash); err == nil { + _ = s.store.TransitionNote(n.ID, NoteUnknown, NoteLive, map[string]interface{}{"reported_msat": n.ValueMsat, "last_error": ""}) + n.State, n.ReportedMsat = NoteLive, n.ValueMsat + prev := un.funding + if i > 0 { + prev = un.dust[i-1] + } + _ = s.store.TransitionNote(prev.ID, "", NoteSpent, nil) + prev.State = NoteSpent + fee := s.mintFee(n.MintID) + change := prev.ReportedMsat - n.ValueMsat - fee.BaseFeeMsat + _ = s.store.TransitionNote(un.dust[i].ID, "", NoteLive, map[string]interface{}{"reported_msat": change, "value_msat": change}) + un.dust[i].State, un.dust[i].ReportedMsat = NoteLive, change + } else if lnurlcash.IsUnknownNote(err) || lnurlcash.IsSpent(err) { + _ = s.store.TransitionNote(n.ID, NoteUnknown, NotePendingCarve, map[string]interface{}{"last_error": ""}) + n.State = NotePendingCarve + } + } + } + if err := s.carve(ctx, b, un, func() {}); err != nil { + log.Warnf("[lnurlcash] recovery: batch %s: %v", b.ID, err) + } + } + s.settleBatchState(b.ID) +} + +// recoverReclaims resolves notes whose melt was sent but not settled. +func (j *Jobs) recoverReclaims(ctx context.Context) { + s := j.svc + notes, err := s.store.NotesByState([]string{NoteReclaiming, NoteUnknown}, []string{KindUser, KindRedeemSplit}, 0) + if err != nil { + return + } + for _, n := range notes { + if ctx.Err() != nil { + return + } + if time.Since(n.UpdatedAt) < 30*time.Second { + continue + } + unlock := lockNote(n.ID) + n, err := s.store.Note(n.ID) + if err != nil { + unlock() + continue + } + if n.InvoiceHash != "" { + paid, err := s.ledger.InvoicePaid(ctx, n.UserName, n.InvoiceHash) + if err == nil && paid { + if st, err := s.settleNoteLocked(n.ID); err == nil && st != nil { + unlock() + if st.Note != nil { + j.notifier.NoteReclaimed(st.Note) + j.notifier.GroupNoteState(st.Note) + } + continue + } + } + } + // not settled: what does the mint say? + _, err = s.client.FetchNoteInfoByHash(ctx, n.MintURL, n.Hash) + switch { + case err == nil: + // the note is outstanding again: the melt failed or never landed + _ = s.store.TransitionNote(n.ID, n.State, NoteLive, map[string]interface{}{"last_error": "melt did not settle; note restored"}) + log.Infof("[lnurlcash] note %s: melt did not settle, note live again", n.ID) + case errors.Is(err, lnurlcash.ErrNotePending): + // still paying; wait + case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err): + // burned, and our invoice is not paid: either the payment is still + // settling on LNbits' side (wait) or somebody else claimed it before + // the melt. The invoice poll above decides on the next run; after a + // day, give up and mark it claimed. + if time.Since(n.UpdatedAt) > 24*time.Hour { + t := time.Now() + _ = s.store.TransitionNote(n.ID, n.State, NoteClaimed, map[string]interface{}{"claimed_at": t, "last_error": "burned without our invoice settling"}) + j.notifier.Alert("LNURLcash note " + n.ID + " was burned but its reclaim invoice never settled; check LNbits payment " + n.InvoiceHash) + } + } + unlock() + } +} + +// recoverRedeems resolves redeems whose melt was sent but not settled. +func (j *Jobs) recoverRedeems(ctx context.Context) { + s := j.svc + redeems, err := s.store.RedeemsByState([]string{RedeemConfirmed, RedeemMelting, RedeemUnknown}) + if err != nil { + return + } + for _, r := range redeems { + if ctx.Err() != nil { + return + } + if time.Since(r.UpdatedAt) < 30*time.Second { + continue + } + unlock := lockNote(r.ID) + r, err := s.store.Redeem(r.ID) + if err != nil { + unlock() + continue + } + if r.State == RedeemConfirmed { + // invoice creation or split died: let the user press again + _ = s.store.TransitionRedeem(r.ID, RedeemConfirmed, RedeemInfo, nil) + unlock() + continue + } + if r.InvoiceHash != "" { + if paid, err := s.ledger.InvoicePaid(ctx, r.UserName, r.InvoiceHash); err == nil && paid { + if st, err := s.settleRedeemLocked(r.ID); err == nil && st != nil && st.Redeem != nil { + unlock() + j.notifier.RedeemSettled(st.Redeem) + continue + } + } + } + noteURL, err := s.cipher.Open(r.NoteURLEnc) + if err != nil { + unlock() + continue + } + _, err = s.client.FetchNoteInfo(ctx, noteURL) + switch { + case err == nil: + // outstanding again: the melt failed. The user may try again. + _ = s.store.TransitionRedeem(r.ID, r.State, RedeemInfo, map[string]interface{}{"last_error": "melt did not settle"}) + case errors.Is(err, lnurlcash.ErrNotePending): + case lnurlcash.IsSpent(err), lnurlcash.IsUnknownNote(err): + if r.SplitNoteID != nil { + // the external note was split; the melt is on the split note + if sn, err := s.store.Note(*r.SplitNoteID); err == nil { + if _, err := s.client.FetchNoteInfoByHash(ctx, sn.MintURL, sn.Hash); err == nil { + _ = s.store.TransitionRedeem(r.ID, r.State, RedeemInfo, map[string]interface{}{"last_error": "melt did not settle"}) + unlock() + continue + } + } + } + if time.Since(r.UpdatedAt) > 24*time.Hour { + _ = s.store.TransitionRedeem(r.ID, r.State, RedeemFailed, map[string]interface{}{"last_error": "note burned but our invoice never settled"}) + j.notifier.Alert("LNURLcash redeem " + r.ID + " burned its note but the invoice never settled; check LNbits invoice " + r.InvoiceHash) + } + } + unlock() + } +} + +// AutoReclaimOnce reclaims live notes older than auto_reclaim_days. +func (j *Jobs) AutoReclaimOnce(ctx context.Context) { + days := j.svc.cfg.AutoReclaimDays + if days <= 0 { + return + } + notes, err := j.svc.store.LiveNotesOlderThan(time.Now().Add(-time.Duration(days) * 24 * time.Hour)) + if err != nil { + return + } + for _, n := range notes { + if ctx.Err() != nil { + return + } + if _, err := j.svc.Reclaim(ctx, n.ID); err != nil && !errors.Is(err, ErrNoteClaimed) { + log.Warnf("[lnurlcash] auto reclaim %s: %v", n.ID, err) + } + } +} diff --git a/internal/lnurlcash/jobs_test.go b/internal/lnurlcash/jobs_test.go new file mode 100644 index 00000000..04ab1226 --- /dev/null +++ b/internal/lnurlcash/jobs_test.go @@ -0,0 +1,123 @@ +package lnurlcash + +import ( + "context" + "testing" + "time" +) + +type recNotifier struct { + claimed, reclaimed, group []string + digests int + redeems []string +} + +func (r *recNotifier) NoteClaimed(n *Note) { r.claimed = append(r.claimed, n.ID) } +func (r *recNotifier) BatchDigest(b *Batch, c []*Note) { r.digests++ } +func (r *recNotifier) NoteReclaimed(n *Note) { r.reclaimed = append(r.reclaimed, n.ID) } +func (r *recNotifier) RedeemSettled(x *Redeem) { r.redeems = append(r.redeems, x.ID) } +func (r *recNotifier) GroupNoteState(n *Note) { r.group = append(r.group, n.ID) } +func (r *recNotifier) Alert(string) {} + +func TestWatcherNotifiesClaims(t *testing.T) { + h := newHarness(t) + ctx := context.Background() + mint, _ := h.reg.Get("fake") + q, _ := h.svc.Quote(ctx, mint, 100_000, 1) + _, single, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q, ChatID: -100}) + q3, _ := h.svc.Quote(ctx, mint, 100_000, 3) + _, batch, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q3}) + rec := &recNotifier{} + jobs := NewJobs(h.svc, rec) + jobs.WatchOnce(ctx) + if len(rec.claimed) != 0 { + t.Fatal("nothing claimed yet") + } + h.mint.claim(single[0].Hash) + h.mint.claim(batch[1].Hash) + jobs.WatchOnce(ctx) + if len(rec.claimed) != 1 || rec.claimed[0] != single[0].ID || rec.digests != 1 || len(rec.group) != 2 { + t.Fatalf("claimed=%v digests=%d group=%v", rec.claimed, rec.digests, rec.group) + } + jobs.WatchOnce(ctx) + if len(rec.claimed) != 1 || rec.digests != 1 { + t.Fatal("a claim must be reported once") + } +} + +func TestRecoveryFinishesReclaimAndRestoresFailedMelt(t *testing.T) { + h := newHarness(t) + ctx := context.Background() + mint, _ := h.reg.Get("fake") + q, _ := h.svc.Quote(ctx, mint, 100_000, 2) + _, live, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q}) + a, b := live[0], live[1] + ra, _ := h.svc.Reclaim(ctx, a.ID) + rb, _ := h.svc.Reclaim(ctx, b.ID) + // a: melt paid but the webhook was lost; b: the mint's payment failed + h.mint.finishMelt(a.Hash, true) + h.ledger.settleIncoming(ra.InvoiceHash) + h.mint.finishMelt(b.Hash, false) + backdate(t, h.store, a.ID) + backdate(t, h.store, b.ID) + rec := &recNotifier{} + jobs := NewJobs(h.svc, rec) + jobs.RecoverOnce(ctx) + na, _ := h.store.Note(a.ID) + nb, _ := h.store.Note(b.ID) + if na.State != NoteReclaimed || nb.State != NoteLive { + t.Fatalf("a=%s b=%s", na.State, nb.State) + } + if len(rec.reclaimed) != 1 || rec.reclaimed[0] != a.ID { + t.Fatalf("reclaimed notifications: %v", rec.reclaimed) + } + _ = rb +} + +func TestRecoveryResumesCarving(t *testing.T) { + h := newHarness(t) + ctx := context.Background() + mint, _ := h.reg.Get("fake") + q, _ := h.svc.Quote(ctx, mint, 100_000, 3) + // simulate a crash after paying the invoice: run Create with a mint that refuses splits, + // then lift the refusal and let recovery carve + h.mint.refuseSplit = "temporarily unavailable" + batch, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q}) + if err == nil || len(live) != 0 { + t.Fatalf("expected the carve to fail: %v", err) + } + // the notes were marked failed by the handler; a crash would instead leave + // them pending_carve. Put them back to that state to model the crash. + notes, _ := h.store.NotesInBatch(batch.ID) + for _, n := range notes { + if n.Kind != KindFunding { + _ = h.store.TransitionNote(n.ID, "", NotePendingCarve, nil) + } + } + _ = h.store.TransitionBatch(batch.ID, "", BatchCarving, nil) + backdateBatch(t, h.store, batch.ID) + h.mint.refuseSplit = "" + NewJobs(h.svc, nil).RecoverOnce(ctx) + b, _ := h.store.Batch(batch.ID) + if b.State != BatchLive { + t.Fatalf("batch state after recovery: %s", b.State) + } + userNotes, _ := h.store.UserNotes("42", []string{NoteLive}) + if len(userNotes) != 3 { + t.Fatalf("expected 3 live notes, got %d", len(userNotes)) + } +} + +func backdate(t *testing.T, s *Store, id string) { + t.Helper() + if err := s.DB().Model(&Note{}).Where("id = ?", id).Update("updated_at", time.Now().Add(-time.Minute)).Error; err != nil { + t.Fatal(err) + } +} + +func backdateBatch(t *testing.T, s *Store, id string) { + t.Helper() + if err := s.DB().Model(&Batch{}).Where("id = ?", id).Update("updated_at", time.Now().Add(-time.Minute)).Error; err != nil { + t.Fatal(err) + } +} diff --git a/internal/lnurlcash/melt.go b/internal/lnurlcash/melt.go index 5148e194..b82e88b4 100644 --- a/internal/lnurlcash/melt.go +++ b/internal/lnurlcash/melt.go @@ -120,41 +120,57 @@ func (s *Service) SettleInvoice(ctx context.Context, hash string) (*Settlement, if n, err := s.store.NoteByInvoiceHash(hash); err == nil { unlock := lockNote(n.ID) defer unlock() - n, _ = s.store.Note(n.ID) - if n.State == NoteReclaimed { - return nil, nil - } - t := s.now() - if err := s.store.TransitionNote(n.ID, "", NoteReclaimed, map[string]interface{}{"reclaimed_at": t, "last_error": ""}); err != nil { - return nil, err - } - n.State, n.ReclaimedAt = NoteReclaimed, &t - if n.BatchID != nil { - s.settleBatchState(*n.BatchID) - } - log.Infof("[lnurlcash] note %s reclaimed (%d msat)", n.ID, n.ReportedMsat) - return &Settlement{Note: n}, nil + return s.settleNoteLocked(n.ID) } if r, err := s.store.RedeemByInvoiceHash(hash); err == nil { unlock := lockNote(r.ID) defer unlock() - r, _ = s.store.Redeem(r.ID) - if r.State == RedeemSettled { - return nil, nil - } - if err := s.store.TransitionRedeem(r.ID, "", RedeemSettled, map[string]interface{}{"last_error": ""}); err != nil { - return nil, err - } - r.State = RedeemSettled - if r.SplitNoteID != nil { - _ = s.store.TransitionNote(*r.SplitNoteID, "", NoteReclaimed, nil) - } - log.Infof("[lnurlcash] redeem %s settled (%d msat)", r.ID, r.ReportedMsat) - return &Settlement{Redeem: r}, nil + return s.settleRedeemLocked(r.ID) } return nil, nil } +// settleNoteLocked finishes a reclaim. The caller holds the note's lock. +func (s *Service) settleNoteLocked(noteID string) (*Settlement, error) { + n, err := s.store.Note(noteID) + if err != nil { + return nil, err + } + if n.State == NoteReclaimed { + return nil, nil + } + t := s.now() + if err := s.store.TransitionNote(n.ID, "", NoteReclaimed, map[string]interface{}{"reclaimed_at": t, "last_error": ""}); err != nil { + return nil, err + } + n.State, n.ReclaimedAt = NoteReclaimed, &t + if n.BatchID != nil { + s.settleBatchState(*n.BatchID) + } + log.Infof("[lnurlcash] note %s reclaimed (%d msat)", n.ID, n.ReportedMsat) + return &Settlement{Note: n}, nil +} + +// settleRedeemLocked finishes a redeem. The caller holds the redeem's lock. +func (s *Service) settleRedeemLocked(redeemID string) (*Settlement, error) { + r, err := s.store.Redeem(redeemID) + if err != nil { + return nil, err + } + if r.State == RedeemSettled { + return nil, nil + } + if err := s.store.TransitionRedeem(r.ID, "", RedeemSettled, map[string]interface{}{"last_error": ""}); err != nil { + return nil, err + } + r.State = RedeemSettled + if r.SplitNoteID != nil { + _ = s.store.TransitionNote(*r.SplitNoteID, "", NoteReclaimed, nil) + } + log.Infof("[lnurlcash] redeem %s settled (%d msat)", r.ID, r.ReportedMsat) + return &Settlement{Redeem: r}, nil +} + // ---- redeem ---- // RedeemPreview is what the user sees before adding a note to their balance.