Return value stranded by a failed note batch to its owner

A refused split after the funding invoice was paid left the funding or
change note in a bot-held row that nothing melted back. A job now splits off
the whole-sat part if needed and reclaims it to the owner's balance, retrying
hourly and alerting the operator once when it cannot.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-14 18:27:53 +00:00
co-authored by Claude Sonnet 5.5
parent b6178e335d
commit cd511cd7cc
4 changed files with 325 additions and 2 deletions
+1
View File
@@ -6,3 +6,4 @@ data/*
/LightningTipBot
*.tar.gz
cashu/node_modules/
trace_*.txt
+5 -2
View File
@@ -35,8 +35,10 @@ type Jobs struct {
// perRun caps how many notes one watcher run probes.
perRun int
watchMu sync.Mutex
recoverMu sync.Mutex
watchMu sync.Mutex
recoverMu sync.Mutex
refundMu sync.Mutex
refundRetry map[string]time.Time
}
// NewJobs wires the jobs. notifier may be nil (then nothing is sent).
@@ -61,6 +63,7 @@ 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, 10*time.Minute, j.RefundStrandedOnce)
go j.loop(ctx, cfg.StatusPollInterval, j.WatchOnce)
if cfg.AutoReclaimDays > 0 {
go j.loop(ctx, 24*time.Hour, j.AutoReclaimOnce)
+207
View File
@@ -0,0 +1,207 @@
package lnurlcash
import (
"context"
"errors"
"fmt"
"strings"
"time"
lnurlcash "github.com/lnurlcash/lnurlcash-go"
log "github.com/sirupsen/logrus"
)
// StrandedCandidates returns live funding and change notes that hold at least
// one whole sat and belong to a batch.
func (s *Store) StrandedCandidates(limit int) ([]*Note, error) {
var notes []*Note
q := s.db.Where("state = ? AND kind IN ? AND batch_id IS NOT NULL AND reported_msat >= ?", NoteLive, []string{KindFunding, KindDust}, 1000).
Order("created_at asc")
if limit > 0 {
q = q.Limit(limit)
}
return notes, q.Find(&notes).Error
}
// batchStranded reports whether a batch ended without delivering every note.
// Only then is the value left in its funding and change notes the owner's.
func (s *Service) batchStranded(b *Batch) bool {
if b.State == BatchFailed {
return true
}
notes, err := s.store.NotesInBatch(b.ID)
if err != nil {
return false
}
for _, n := range notes {
if n.Kind == KindUser && n.State == NoteFailed {
return true
}
}
return false
}
// RefundStranded melts the value that a failed or partial batch left in a
// bot-held funding or change note back into its owner's balance: the whole-sat
// part is split off if needed and reclaimed like any note. It returns nil when
// there is nothing to do and ErrInFlight/nil once a melt is under way.
func (s *Service) RefundStranded(ctx context.Context, noteID string) error {
var reclaimID string
err := func() error {
unlock := lockNote(noteID)
defer unlock()
n, err := s.store.Note(noteID)
if err != nil {
return err
}
if n.State != NoteLive || n.BatchID == nil || (n.Kind != KindFunding && n.Kind != KindDust) {
return nil
}
b, err := s.store.Batch(*n.BatchID)
if err != nil || !s.batchStranded(b) {
return err
}
state, value, err := s.Status(ctx, n)
if err != nil {
return err
}
if state != NoteLive || value < 1000 {
return nil
}
reclaimID = n.ID
if value%1000 != 0 {
target, err := s.splitOffWholeSats(ctx, n, value)
if err != nil {
reclaimID = ""
return err
}
reclaimID = target.ID
}
return nil
}()
if err != nil || reclaimID == "" {
return err
}
if _, err := s.Reclaim(ctx, reclaimID); err != nil && !errors.Is(err, ErrInFlight) {
return err
}
return nil
}
// splitOffWholeSats splits the largest whole-sat note off n. Both new secrets
// are stored before the split is sent, and a half-finished split is resumed.
func (s *Service) splitOffWholeSats(ctx context.Context, n *Note, value int64) (*Note, error) {
memo := "refund " + n.ID
var target, rest *Note
pending, err := s.store.NotesByState([]string{NotePendingCarve}, []string{KindRedeemSplit, KindDust}, 0)
if err != nil {
return nil, err
}
for _, p := range pending {
if p.Memo == memo && p.Kind == KindRedeemSplit {
target = p
} else if p.Memo == memo {
rest = p
}
}
if target == nil || rest == nil {
mk := func(kind string) (*Note, error) {
secret, err := lnurlcash.GenerateNoteSecret()
if err != nil {
return nil, err
}
h, err := lnurlcash.HashK1(secret)
if err != nil {
return nil, err
}
enc, err := s.cipher.Seal(secret)
if err != nil {
return nil, err
}
return &Note{ID: newID("note"), UserName: n.UserName, MintID: n.MintID, MintURL: n.MintURL,
MintPubkey: n.MintPubkey, Hash: h, SecretEnc: enc, Kind: kind, State: NotePendingCarve,
LanguageCode: n.LanguageCode, Memo: memo}, nil
}
if target, err = mk(KindRedeemSplit); err != nil {
return nil, err
}
if rest, err = mk(KindDust); err != nil {
return nil, err
}
if err := s.store.CreateNotes(nil, []*Note{target, rest}); err != nil {
return nil, err
}
}
k1, err := s.secret(n)
if err != nil {
return nil, err
}
landed := func(amount int64) *Note {
_ = s.store.TransitionNote(target.ID, "", NoteLive, map[string]interface{}{"value_msat": amount, "reported_msat": amount})
target.State, target.ValueMsat, target.ReportedMsat = NoteLive, amount, amount
change := value - amount
if info, perr := s.client.FetchNoteInfoByHash(ctx, n.MintURL, rest.Hash); perr == nil {
change = info.MaxWithdrawableMsat
}
_ = s.store.TransitionNote(rest.ID, "", NoteLive, map[string]interface{}{"value_msat": change, "reported_msat": change})
_ = s.store.TransitionNote(n.ID, "", NoteSpent, nil)
return target
}
for sats := value / 1000; sats > 0; {
amount := sats * 1000
_, err := s.client.SplitNoteWithHash(ctx, n.MintURLCallback(), []string{k1}, amount, target.Hash, rest.Hash)
if err == nil {
return landed(amount), nil
}
if lnurlcash.IsAmbiguous(err) || lnurlcash.IsAlreadyInUse(err) || lnurlcash.IsSpent(err) || lnurlcash.IsUnknownNote(err) {
// the split may have landed: the output decides
if info, perr := s.client.FetchNoteInfoByHash(ctx, n.MintURL, target.Hash); perr == nil {
return landed(info.MaxWithdrawableMsat), nil
}
return nil, fmt.Errorf("refund split of %s unresolved: %w", n.ID, err)
}
if strings.Contains(strings.ToLower(err.Error()), "insufficient") {
sats-- // the mint's fee does not leave room for the full amount
continue
}
return nil, fmt.Errorf("%w: %v", ErrMintUnavailable, err)
}
return nil, ErrFractionalValue
}
// RefundStrandedOnce returns the stranded value of failed batches to their
// owners. A note that cannot be refunded is retried hourly and reported to the
// operator once.
func (j *Jobs) RefundStrandedOnce(ctx context.Context) {
if !j.refundMu.TryLock() {
return
}
defer j.refundMu.Unlock()
notes, err := j.svc.store.StrandedCandidates(j.perRun)
if err != nil {
log.Errorf("[lnurlcash] refund: %v", err)
return
}
for _, n := range notes {
if ctx.Err() != nil {
return
}
if next, ok := j.refundRetry[n.ID]; ok && time.Now().Before(next) {
continue
}
err := j.svc.RefundStranded(ctx, n.ID)
if err == nil {
delete(j.refundRetry, n.ID)
continue
}
if j.refundRetry == nil {
j.refundRetry = map[string]time.Time{}
}
_, seen := j.refundRetry[n.ID]
j.refundRetry[n.ID] = time.Now().Add(time.Hour)
log.Warnf("[lnurlcash] refund of %s failed: %v", n.ID, err)
if !seen {
j.notifier.Alert(fmt.Sprintf("LNURLcash could not return %d msat held in note %s of a failed batch to user %s: %v", n.ReportedMsat, n.ID, n.UserName, err))
}
}
}
+112
View File
@@ -0,0 +1,112 @@
package lnurlcash
import (
"context"
"net/http"
"testing"
"time"
)
func backdateAll(h *harness) {
old := time.Now().Add(-time.Hour)
h.store.DB().Exec("UPDATE lnurlcash_batches SET updated_at = ?", old)
h.store.DB().Exec("UPDATE lnurlcash_notes SET updated_at = ?", old)
}
// settleRefunds pays every pending reclaim invoice, as the melt would.
func settleRefunds(t *testing.T, h *harness) int {
n := 0
for hash, inv := range h.ledger.invoices {
if !inv.paid && len(inv.ref) > len(RefNote) && inv.ref[:len(RefNote)] == RefNote {
h.ledger.settleIncoming(hash)
if _, err := h.svc.SettleInvoice(context.Background(), hash); err != nil {
t.Fatal(err)
}
n++
}
}
return n
}
// A split refused after the funding invoice was paid must not keep the value:
// the refund job returns it to the owner.
func TestRefundStrandedAfterCarveFailure(t *testing.T) {
for _, mode := range []string{"total", "partial"} {
t.Run(mode, func(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, err := h.svc.Quote(ctx, mint, 100_000, 3)
if err != nil {
t.Fatal(err)
}
start := h.ledger.balances["42"]
wantLive, wantState := 0, BatchFailed
if mode == "total" {
h.mint.mu.Lock()
h.mint.refuseSplit = "service busy"
h.mint.mu.Unlock()
} else {
// the mint accepts the first split and refuses the second
wantLive, wantState = 1, BatchPartial
orig := h.mint.srv.Config.Handler
splits := 0
h.mint.srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
qs := r.URL.Query()
if r.URL.Path == "/w" && qs.Get("p1") != "" && qs.Get("amount") != "" {
splits++
if splits == 2 {
h.mint.mu.Lock()
h.mint.refuseSplit = "service busy"
h.mint.mu.Unlock()
}
}
orig.ServeHTTP(w, r)
})
}
batch, live, _ := h.svc.Create(ctx, CreateParams{User: "42", Quote: q})
if len(live) != wantLive || batch.State != wantState {
t.Fatalf("setup: live=%d state=%s", len(live), batch.State)
}
h.mint.mu.Lock()
h.mint.refuseSplit = ""
h.mint.mu.Unlock()
debited := start - h.ledger.balances["42"]
if debited != q.GrossMsat {
t.Fatalf("debited %d, gross %d", debited, q.GrossMsat)
}
backdateAll(h)
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) == 0 {
t.Fatal("no refund invoice was created")
}
// everything but the delivered notes and the mint fees paid in the gross is back
delivered := int64(wantLive) * 100_000
if lost := start - h.ledger.balances["42"] - delivered; lost > q.GrossMsat-3*100_000 {
t.Errorf("user lost %d msat of %d", lost, q.GrossMsat)
}
// a second run must not pay out again
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) != 0 {
t.Error("refund was repeated")
}
})
}
}
// Value of healthy batches (the dust left after a full carve) is not refunded.
func TestRefundIgnoresHealthyBatches(t *testing.T) {
h := newHarness(t)
ctx := context.Background()
mint, _ := h.reg.Get("fake")
q, _ := h.svc.Quote(ctx, mint, 100_000, 3)
if _, live, err := h.svc.Create(ctx, CreateParams{User: "42", Quote: q}); err != nil || len(live) != 3 {
t.Fatalf("create: live=%d err=%v", len(live), err)
}
backdateAll(h)
NewJobs(h.svc, nil).RefundStrandedOnce(ctx)
if settleRefunds(t, h) != 0 {
t.Error("a healthy batch was refunded")
}
}