package main // Settlement watcher for zaps. // // Zap receipts can only be published once the invoice is actually paid, and the // zap request is only needed at that moment. Two independent sources detect // settlement: // // - NIP-47 payment_received notifications (fast path, seconds) // - a periodic lookup_invoice sweep (fallback, and the only path if a // notification is missed because the listener was disconnected) // // Both funnel into settleZap, which is idempotent: the state store records the // receipt event id per payment hash, so a zap is never receipted twice. import ( "context" "log" "time" ) const ( // zapSweepInterval is how often unpaid zaps are re-checked. zapSweepInterval = 30 * time.Second // zapExpiry drops a pending zap that was never paid. Invoices are valid for // 24h, but an unpaid zap is far more likely abandoned than late, and every // pending entry costs a lookup_invoice call per sweep. Settlement is still // detected after this window via a payment_received notification, because // settleZap resolves the zap by payment hash independently of the sweep. zapExpiry = 2 * time.Hour // zapSweepBatch bounds how many lookups one sweep issues. zapSweepBatch = 25 // zapLookupTimeout bounds a single lookup_invoice exchange. zapLookupTimeout = 25 * time.Second ) // runZapWatcher blocks until ctx ends, settling zaps as they are paid. func runZapWatcher(ctx context.Context) { if zapServer == nil { return } // Fast path: notifications from the wallet. go nwc.listenNotifications(ctx, func(n NWCNotification) { if n.PaymentHash == "" { return } if !zapServer.hasPending(n.PaymentHash) { return } log.Printf("zap: notification %s for %s", n.Type, n.PaymentHash) settleZap(ctx, n.PaymentHash, n.Preimage) }) // Fallback: periodic sweep so a missed notification still gets receipted. ticker := time.NewTicker(zapSweepInterval) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: sweepZaps(ctx) } } } // sweepZaps checks every pending zap's invoice state. func sweepZaps(ctx context.Context) { pending := zapServer.pendingList() if len(pending) == 0 { return } // Drop zaps whose invoices have expired rather than asking the wallet about // them forever. now := time.Now() checked := 0 for _, p := range pending { if now.Sub(p.CreatedAt) > zapExpiry { log.Printf("zap: dropping expired pending zap %s", p.PaymentHash) _ = zapServer.forget(p.PaymentHash) continue } if checked >= zapSweepBatch { break } checked++ lookupCtx, cancel := context.WithTimeout(ctx, zapLookupTimeout) res, err := nwc.lookupInvoice(lookupCtx, p.PaymentHash, p.Invoice) cancel() if err != nil { log.Printf("zap: lookup %s failed: %v", p.PaymentHash, err) continue } if isSettled(res) { settleZap(ctx, p.PaymentHash, res.Preimage) } } } // isSettled reports whether an invoice is paid. The preimage is the strongest // signal (only the recipient can know it), with state as a fallback. func isSettled(res *LookupInvoiceResult) bool { if res == nil { return false } if res.Preimage != "" { return true } return res.State == "settled" } // settleZap publishes the receipt for a settled zap exactly once. func settleZap(ctx context.Context, paymentHash, preimage string) { if zapServer.alreadyReceipted(paymentHash) { return } p := zapServer.pending(paymentHash) if p == nil { return } var zr ZapRequest if err := jsonUnmarshalStrict(p.ZapRequest, &zr); err != nil { log.Printf("zap: stored zap request for %s is unreadable: %v", paymentHash, err) _ = zapServer.forget(paymentHash) return } paidAt := time.Now() ev, err := zapServer.buildReceipt(&zr, p.ZapRequest, p.Invoice, preimage, paidAt) if err != nil { log.Printf("zap: build receipt for %s failed: %v", paymentHash, err) return } pubCtx, cancel := context.WithTimeout(ctx, 60*time.Second) defer cancel() if err := publishReceipt(pubCtx, ev, p.Relays); err != nil { // Leave it pending so the sweep retries; a transient relay outage should // not silently cost the sender their receipt. log.Printf("zap: receipt for %s not published: %v", paymentHash, err) return } if err := zapServer.markReceipted(paymentHash, ev.ID); err != nil { log.Printf("zap: failed to record receipt %s: %v", ev.ID, err) } log.Printf("zap: receipt %s published for %s (%d msat)", ev.ID, paymentHash, p.AmountMsat) }