zapwatch.go raw

   1  package main
   2  
   3  // Settlement watcher for zaps.
   4  //
   5  // Zap receipts can only be published once the invoice is actually paid, and the
   6  // zap request is only needed at that moment. Two independent sources detect
   7  // settlement:
   8  //
   9  //   - NIP-47 payment_received notifications (fast path, seconds)
  10  //   - a periodic lookup_invoice sweep (fallback, and the only path if a
  11  //     notification is missed because the listener was disconnected)
  12  //
  13  // Both funnel into settleZap, which is idempotent: the state store records the
  14  // receipt event id per payment hash, so a zap is never receipted twice.
  15  
  16  import (
  17  	"context"
  18  	"log"
  19  	"time"
  20  )
  21  
  22  const (
  23  	// zapSweepInterval is how often unpaid zaps are re-checked.
  24  	zapSweepInterval = 30 * time.Second
  25  	// zapExpiry drops a pending zap that was never paid. Invoices are valid for
  26  	// 24h, but an unpaid zap is far more likely abandoned than late, and every
  27  	// pending entry costs a lookup_invoice call per sweep. Settlement is still
  28  	// detected after this window via a payment_received notification, because
  29  	// settleZap resolves the zap by payment hash independently of the sweep.
  30  	zapExpiry = 2 * time.Hour
  31  	// zapSweepBatch bounds how many lookups one sweep issues.
  32  	zapSweepBatch = 25
  33  	// zapLookupTimeout bounds a single lookup_invoice exchange.
  34  	zapLookupTimeout = 25 * time.Second
  35  )
  36  
  37  // runZapWatcher blocks until ctx ends, settling zaps as they are paid.
  38  func runZapWatcher(ctx context.Context) {
  39  	if zapServer == nil {
  40  		return
  41  	}
  42  
  43  	// Fast path: notifications from the wallet.
  44  	go nwc.listenNotifications(ctx, func(n NWCNotification) {
  45  		if n.PaymentHash == "" {
  46  			return
  47  		}
  48  		if !zapServer.hasPending(n.PaymentHash) {
  49  			return
  50  		}
  51  		log.Printf("zap: notification %s for %s", n.Type, n.PaymentHash)
  52  		settleZap(ctx, n.PaymentHash, n.Preimage)
  53  	})
  54  
  55  	// Fallback: periodic sweep so a missed notification still gets receipted.
  56  	ticker := time.NewTicker(zapSweepInterval)
  57  	defer ticker.Stop()
  58  	for {
  59  		select {
  60  		case <-ctx.Done():
  61  			return
  62  		case <-ticker.C:
  63  			sweepZaps(ctx)
  64  		}
  65  	}
  66  }
  67  
  68  // sweepZaps checks every pending zap's invoice state.
  69  func sweepZaps(ctx context.Context) {
  70  	pending := zapServer.pendingList()
  71  	if len(pending) == 0 {
  72  		return
  73  	}
  74  
  75  	// Drop zaps whose invoices have expired rather than asking the wallet about
  76  	// them forever.
  77  	now := time.Now()
  78  	checked := 0
  79  	for _, p := range pending {
  80  		if now.Sub(p.CreatedAt) > zapExpiry {
  81  			log.Printf("zap: dropping expired pending zap %s", p.PaymentHash)
  82  			_ = zapServer.forget(p.PaymentHash)
  83  			continue
  84  		}
  85  		if checked >= zapSweepBatch {
  86  			break
  87  		}
  88  		checked++
  89  
  90  		lookupCtx, cancel := context.WithTimeout(ctx, zapLookupTimeout)
  91  		res, err := nwc.lookupInvoice(lookupCtx, p.PaymentHash, p.Invoice)
  92  		cancel()
  93  		if err != nil {
  94  			log.Printf("zap: lookup %s failed: %v", p.PaymentHash, err)
  95  			continue
  96  		}
  97  		if isSettled(res) {
  98  			settleZap(ctx, p.PaymentHash, res.Preimage)
  99  		}
 100  	}
 101  }
 102  
 103  // isSettled reports whether an invoice is paid. The preimage is the strongest
 104  // signal (only the recipient can know it), with state as a fallback.
 105  func isSettled(res *LookupInvoiceResult) bool {
 106  	if res == nil {
 107  		return false
 108  	}
 109  	if res.Preimage != "" {
 110  		return true
 111  	}
 112  	return res.State == "settled"
 113  }
 114  
 115  // settleZap publishes the receipt for a settled zap exactly once.
 116  func settleZap(ctx context.Context, paymentHash, preimage string) {
 117  	if zapServer.alreadyReceipted(paymentHash) {
 118  		return
 119  	}
 120  	p := zapServer.pending(paymentHash)
 121  	if p == nil {
 122  		return
 123  	}
 124  
 125  	var zr ZapRequest
 126  	if err := jsonUnmarshalStrict(p.ZapRequest, &zr); err != nil {
 127  		log.Printf("zap: stored zap request for %s is unreadable: %v", paymentHash, err)
 128  		_ = zapServer.forget(paymentHash)
 129  		return
 130  	}
 131  
 132  	paidAt := time.Now()
 133  	ev, err := zapServer.buildReceipt(&zr, p.ZapRequest, p.Invoice, preimage, paidAt)
 134  	if err != nil {
 135  		log.Printf("zap: build receipt for %s failed: %v", paymentHash, err)
 136  		return
 137  	}
 138  
 139  	pubCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
 140  	defer cancel()
 141  	if err := publishReceipt(pubCtx, ev, p.Relays); err != nil {
 142  		// Leave it pending so the sweep retries; a transient relay outage should
 143  		// not silently cost the sender their receipt.
 144  		log.Printf("zap: receipt for %s not published: %v", paymentHash, err)
 145  		return
 146  	}
 147  	if err := zapServer.markReceipted(paymentHash, ev.ID); err != nil {
 148  		log.Printf("zap: failed to record receipt %s: %v", ev.ID, err)
 149  	}
 150  	log.Printf("zap: receipt %s published for %s (%d msat)", ev.ID, paymentHash, p.AmountMsat)
 151  }
 152