1 package main
2 3 // NIP-57 Lightning zaps.
4 //
5 // The flow implemented here (NIP-57 steps 1-8):
6 //
7 // 1. The payRequest response advertises allowsNostr + nostrPubkey.
8 // 2. A client sends a signed kind 9734 zap request to the callback as the
9 // `nostr` query parameter.
10 // 3. The callback validates it and asks the wallet for an invoice whose
11 // description_hash is sha256 of the zap request note and nothing else.
12 // 4. The zap request is persisted against the invoice payment hash.
13 // 5. When the invoice settles, THIS SERVER (not the wallet) publishes a kind
14 // 9735 receipt to the relays named in the zap request, signed with the key
15 // advertised as nostrPubkey.
16 //
17 // Step 5 is server-side by definition: the wallet only ever sees an opaque
18 // description hash, so it cannot construct a receipt.
19 20 import (
21 "context"
22 "crypto/sha256"
23 "encoding/hex"
24 "encoding/json"
25 "fmt"
26 "log"
27 "os"
28 "path/filepath"
29 "sort"
30 "strings"
31 "sync"
32 "time"
33 34 "github.com/nbd-wtf/go-nostr"
35 )
36 37 const (
38 zapRequestKind = 9734
39 zapReceiptKind = 9735
40 41 // bolt11TagPaymentHash is the raw 5-bit value of the 'p' tag type
42 // ('p' = 1 in the bech32 charset), and a 32-byte value occupies 52 groups.
43 bolt11TagPaymentHash = 1
44 bolt11PaymentHashGroups = 52
45 )
46 47 // deriveKey deterministically derives a 32-byte secret key from a base secret and
48 // a domain-separation label, so the receipt identity survives restarts without
49 // requiring a separate secret to be provisioned.
50 func deriveKey(label, base string) string {
51 h := sha256.Sum256([]byte(label + "\x00" + base))
52 return hex.EncodeToString(h[:])
53 }
54 55 // ZapRequest is the subset of a kind 9734 event this server needs. Tags are
56 // kept raw so the exact received bytes can be hashed for the description hash.
57 type ZapRequest struct {
58 ID string `json:"id"`
59 PubKey string `json:"pubkey"`
60 CreatedAt int64 `json:"created_at"`
61 Kind int `json:"kind"`
62 Tags [][]string `json:"tags"`
63 Content string `json:"content"`
64 Sig string `json:"sig"`
65 }
66 67 // validateZapRequest performs the Appendix D checks. It returns the relays to
68 // publish the receipt to.
69 func validateZapRequest(zr *ZapRequest, amountMsat uint64, callbackHost string) (relays []string, err error) {
70 if zr.Kind != zapRequestKind {
71 return nil, fmt.Errorf("zap request kind is %d, want %d", zr.Kind, zapRequestKind)
72 }
73 if len(zr.ID) != 64 || len(zr.PubKey) != 64 || len(zr.Sig) != 128 {
74 return nil, fmt.Errorf("zap request has malformed id/pubkey/sig")
75 }
76 if len(zr.Tags) == 0 {
77 return nil, fmt.Errorf("zap request has no tags")
78 }
79 80 var (
81 pTags []string
82 eTags int
83 pUpper []string
84 amountTag string
85 hasAmount bool
86 )
87 for _, t := range zr.Tags {
88 if len(t) == 0 {
89 continue
90 }
91 switch t[0] {
92 case "relays":
93 for _, r := range t[1:] {
94 if strings.HasPrefix(r, "wss://") || strings.HasPrefix(r, "ws://") {
95 relays = append(relays, r)
96 }
97 }
98 case "p":
99 if len(t) >= 2 {
100 pTags = append(pTags, t[1])
101 }
102 case "P":
103 if len(t) >= 2 {
104 pUpper = append(pUpper, t[1])
105 }
106 case "e":
107 eTags++
108 case "amount":
109 if len(t) >= 2 {
110 amountTag = t[1]
111 hasAmount = true
112 }
113 }
114 }
115 116 // NIP-57 Appendix D.3
117 if len(pTags) != 1 {
118 return nil, fmt.Errorf("zap request must have exactly one p tag, has %d", len(pTags))
119 }
120 // D.4
121 if eTags > 1 {
122 return nil, fmt.Errorf("zap request must have at most one e tag, has %d", eTags)
123 }
124 // D.5
125 if len(relays) == 0 {
126 return nil, fmt.Errorf("zap request has no usable relays tag")
127 }
128 // D.6
129 if hasAmount && amountTag != fmt.Sprintf("%d", amountMsat) {
130 return nil, fmt.Errorf("zap request amount tag %q does not match amount %d", amountTag, amountMsat)
131 }
132 // D.8
133 if len(pUpper) > 1 {
134 return nil, fmt.Errorf("zap request must have at most one P tag, has %d", len(pUpper))
135 }
136 137 // D.1 - the signature must actually verify, otherwise anyone could mint
138 // receipts by fabricating zap requests.
139 tags := make(nostr.Tags, 0, len(zr.Tags))
140 for _, t := range zr.Tags {
141 tags = append(tags, nostr.Tag(t))
142 }
143 ev := nostr.Event{
144 ID: zr.ID,
145 PubKey: zr.PubKey,
146 CreatedAt: nostr.Timestamp(zr.CreatedAt),
147 Kind: zapRequestKind,
148 Tags: tags,
149 Content: zr.Content,
150 Sig: zr.Sig,
151 }
152 ok, verr := ev.CheckSignature()
153 if verr != nil {
154 return nil, fmt.Errorf("zap request signature is invalid: %w", verr)
155 }
156 if !ok {
157 return nil, fmt.Errorf("zap request signature is invalid")
158 }
159 // CheckSignature only ties sig -> id -> pubkey; it does NOT check that the id
160 // is the hash of the event content. The id is what the invoice description
161 // hash commits to (via the canonical re-serialisation), so a mismatched id
162 // must be rejected or a client could have the receipt commit to a bogus id.
163 if ev.GetID() != zr.ID {
164 return nil, fmt.Errorf("zap request id does not match its content")
165 }
166 167 // Reject requests that are not for this endpoint, when an lnurl tag is
168 // present (D-recommended). Cheap sanity check, no bech32 needed.
169 for _, t := range zr.Tags {
170 if len(t) >= 2 && t[0] == "lnurl" {
171 if !strings.HasPrefix(strings.ToLower(t[1]), "lnurl1") {
172 return nil, fmt.Errorf("zap request lnurl tag is not an lnurl")
173 }
174 }
175 }
176 177 // Bound clock skew so a stale or far-future request cannot be replayed.
178 now := time.Now().Unix()
179 if zr.CreatedAt < now-3600 || zr.CreatedAt > now+600 {
180 return nil, fmt.Errorf("zap request created_at %d is not recent", zr.CreatedAt)
181 }
182 183 // Deduplicate and cap the relay list we will publish to.
184 seen := map[string]bool{}
185 uniq := relays[:0]
186 for _, r := range relays {
187 if !seen[r] {
188 seen[r] = true
189 uniq = append(uniq, r)
190 }
191 }
192 if len(uniq) > 16 {
193 uniq = uniq[:16]
194 }
195 return uniq, nil
196 }
197 198 // parseAndValidateZap decodes the `nostr` query parameter into a ZapRequest and
199 // applies the NIP-57 Appendix D checks.
200 //
201 // It returns the CANONICAL serialization of the validated event rather than the
202 // raw query bytes. The event id and signature only commit to the canonical
203 // encoding, so hashing arbitrary client-supplied bytes would let a client commit
204 // the invoice (and therefore the receipt) to text that no valid zap request
205 // verifies against.
206 func parseAndValidateZap(raw string, amountMsat uint64) (*ZapRequest, string, []string, error) {
207 var zr ZapRequest
208 dec := json.NewDecoder(strings.NewReader(raw))
209 dec.UseNumber()
210 if err := dec.Decode(&zr); err != nil {
211 return nil, "", nil, fmt.Errorf("zap request is not valid JSON: %w", err)
212 }
213 relays, err := validateZapRequest(&zr, amountMsat, "")
214 if err != nil {
215 return nil, "", nil, err
216 }
217 return &zr, canonicalZapRequest(&zr), relays, nil
218 }
219 220 // canonicalZapRequest rebuilds the exact JSON encoding the event id and
221 // signature are computed over, so hashing it is equivalent to hashing the
222 // verified event.
223 func canonicalZapRequest(zr *ZapRequest) string {
224 return zapEvent(zr).String()
225 }
226 227 // zapEvent converts a parsed zap request back into a nostr event.
228 func zapEvent(zr *ZapRequest) *nostr.Event {
229 tags := make(nostr.Tags, 0, len(zr.Tags))
230 for _, t := range zr.Tags {
231 tags = append(tags, nostr.Tag(t))
232 }
233 return &nostr.Event{
234 ID: zr.ID,
235 PubKey: zr.PubKey,
236 CreatedAt: nostr.Timestamp(zr.CreatedAt),
237 Kind: zapRequestKind,
238 Tags: tags,
239 Content: zr.Content,
240 Sig: zr.Sig,
241 }
242 }
243 244 // --- minimal bolt11 payment-hash extraction ---------------------------------
245 //
246 // A full bolt11 decoder is a large dependency (the available one pulls in lnd,
247 // etcd and docker), but the zap flow needs exactly one field: the payment hash
248 // (`p` tag), which is the SHA256 of the payment preimage and is what
249 // lookup_invoice keys on. This is a self-contained bech32 + tagged-field reader
250 // for that one field, covered by a test against a real invoice.
251 252 const bech32Charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
253 254 // bech32DataPart returns the 5-bit data groups of a bech32 string, excluding the
255 // 6-character checksum.
256 func bech32DataPart(s string) ([]byte, error) {
257 s = strings.ToLower(strings.TrimSpace(s))
258 pos := strings.LastIndexByte(s, '1')
259 if pos < 1 || pos+7 > len(s) {
260 return nil, fmt.Errorf("not a bech32 string")
261 }
262 out := make([]byte, 0, len(s)-pos-1)
263 for i := pos + 1; i < len(s); i++ {
264 idx := strings.IndexByte(bech32Charset, s[i])
265 if idx < 0 {
266 return nil, fmt.Errorf("invalid bech32 character %q", s[i])
267 }
268 out = append(out, byte(idx))
269 }
270 return out[:len(out)-6], nil
271 }
272 273 // bitsToBytes repacks 5-bit groups into bytes. pad must be false when the total
274 // bit count is not a multiple of 8, which is the case for a bolt11 data part.
275 func bitsToBytes(values []byte, pad bool) []byte {
276 var (
277 acc uint32
278 bits uint
279 out []byte
280 )
281 for _, v := range values {
282 acc = acc<<5 | uint32(v)
283 bits += 5
284 for bits >= 8 {
285 bits -= 8
286 out = append(out, byte(acc>>bits))
287 }
288 }
289 if pad && bits > 0 {
290 out = append(out, byte(acc<<(8-bits)))
291 }
292 return out
293 }
294 295 // paymentHashFromInvoice extracts the payment hash (the `p` tagged field) from a
296 // BOLT11 invoice.
297 //
298 // Details of the encoding that are easy to get wrong:
299 // - the bech32 data part excludes the 6 checksum groups but INCLUDES the
300 // trailing 104-group ECDSA signature, which must be dropped before walking
301 // the tagged fields;
302 // - the timestamp is the first 7 groups (35 bits);
303 // - each tagged field is: ONE group of type, TWO groups of length, then
304 // `length` groups of value - the length counts 5-bit groups, not bytes, so a
305 // 32-byte value has length 52.
306 //
307 // Verified against a real invoice by TestPaymentHashFromInvoice.
308 func paymentHashFromInvoice(invoice string) (string, error) {
309 groups, err := bech32DataPart(invoice)
310 if err != nil {
311 return "", err
312 }
313 // Drop the 104-group signature to leave the timestamp and tagged fields.
314 if len(groups) <= 104 {
315 return "", fmt.Errorf("invoice data too short")
316 }
317 data := groups[:len(groups)-104]
318 319 // 7 groups of 5 bits hold the 35-bit timestamp.
320 const timestampGroups = 7
321 if len(data) < timestampGroups {
322 return "", fmt.Errorf("invoice too short for a timestamp")
323 }
324 325 i := timestampGroups
326 for i+3 <= len(data) {
327 tag := data[i]
328 length := int(data[i+1])<<5 | int(data[i+2])
329 i += 3
330 if length <= 0 || i+length > len(data) {
331 // Malformed or trailing field; nothing further we can read.
332 break
333 }
334 value := data[i : i+length]
335 i += length
336 337 if tag == bolt11TagPaymentHash {
338 if length != bolt11PaymentHashGroups {
339 return "", fmt.Errorf("payment hash field has %d groups, want %d",
340 length, bolt11PaymentHashGroups)
341 }
342 raw := bitsToBytes(value, false)
343 if len(raw) != 32 {
344 return "", fmt.Errorf("payment hash decoded to %d bytes, want 32", len(raw))
345 }
346 return hex.EncodeToString(raw), nil
347 }
348 }
349 return "", fmt.Errorf("invoice has no payment hash tag")
350 }
351 352 // pendingZap is a zap request awaiting settlement.
353 type pendingZap struct {
354 PaymentHash string `json:"payment_hash"`
355 ZapRequest string `json:"zap_request"` // exact bytes received, for the description tag
356 Relays []string `json:"relays"`
357 AmountMsat uint64 `json:"amount_msat"`
358 Invoice string `json:"invoice"`
359 CreatedAt time.Time `json:"created_at"`
360 }
361 362 // zapState is the on-disk record of zaps awaiting settlement plus the receipts
363 // already published, so a restart neither loses a zap nor double-publishes one.
364 type zapState struct {
365 Pending map[string]*pendingZap `json:"pending"`
366 Receipts map[string]string `json:"receipts"` // payment hash -> receipt event id
367 }
368 369 // ZapServer holds the receipt-signing identity and the pending-zap store.
370 type ZapServer struct {
371 secret string
372 pubkey string
373 374 mu sync.Mutex
375 state zapState
376 path string
377 }
378 379 // loadOrCreateZapKey returns a stable receipt-signing key. ZAP_SECRET (hex) wins;
380 // otherwise the key is derived deterministically from the NWC secret so restarts
381 // do not change the advertised nostrPubkey (clients reject a receipt whose
382 // pubkey differs from the advertised one).
383 func loadOrCreateZapKey(nwcSecret string) (string, error) {
384 if s := strings.TrimSpace(os.Getenv("ZAP_SECRET")); s != "" {
385 if len(s) != 64 {
386 return "", fmt.Errorf("ZAP_SECRET must be 64 hex characters")
387 }
388 return s, nil
389 }
390 if nwcSecret == "" {
391 return "", fmt.Errorf("no ZAP_SECRET and no NWC secret to derive from")
392 }
393 return deriveKey("lnurl-server/zap-receipt", nwcSecret), nil
394 }
395 396 func newZapServer(nwcSecret, path string) (*ZapServer, error) {
397 sk, err := loadOrCreateZapKey(nwcSecret)
398 if err != nil {
399 return nil, err
400 }
401 pk, err := nostr.GetPublicKey(sk)
402 if err != nil {
403 return nil, fmt.Errorf("derive zap pubkey: %w", err)
404 }
405 z := &ZapServer{
406 secret: sk,
407 pubkey: pk,
408 path: path,
409 state: zapState{
410 Pending: map[string]*pendingZap{},
411 Receipts: map[string]string{},
412 },
413 }
414 if err := z.load(); err != nil {
415 log.Printf("zap state load: %v (starting empty)", err)
416 }
417 return z, nil
418 }
419 420 func (z *ZapServer) load() error {
421 if z.path == "" {
422 return nil
423 }
424 b, err := os.ReadFile(z.path)
425 if err != nil {
426 if os.IsNotExist(err) {
427 return nil
428 }
429 return err
430 }
431 var st zapState
432 if err := json.Unmarshal(b, &st); err != nil {
433 return err
434 }
435 if st.Pending == nil {
436 st.Pending = map[string]*pendingZap{}
437 }
438 if st.Receipts == nil {
439 st.Receipts = map[string]string{}
440 }
441 z.mu.Lock()
442 z.state = st
443 z.mu.Unlock()
444 return nil
445 }
446 447 // save persists state atomically (write temp + rename) so a crash mid-write
448 // cannot corrupt the store.
449 func (z *ZapServer) save() error {
450 if z.path == "" {
451 return nil
452 }
453 z.mu.Lock()
454 b, err := json.MarshalIndent(z.state, "", " ")
455 z.mu.Unlock()
456 if err != nil {
457 return err
458 }
459 dir := filepath.Dir(z.path)
460 if err := os.MkdirAll(dir, 0o700); err != nil {
461 return err
462 }
463 tmp, err := os.CreateTemp(dir, ".zaps-*.tmp")
464 if err != nil {
465 return err
466 }
467 defer os.Remove(tmp.Name())
468 if _, err := tmp.Write(b); err != nil {
469 tmp.Close()
470 return err
471 }
472 if err := tmp.Sync(); err != nil {
473 tmp.Close()
474 return err
475 }
476 if err := tmp.Close(); err != nil {
477 return err
478 }
479 return os.Rename(tmp.Name(), z.path)
480 }
481 482 // maxPendingZaps bounds how much unpaid-zap state is retained, so a client that
483 // requests invoices without paying cannot grow the store (and the sweep work)
484 // without limit. Entries also expire by age in the watcher.
485 const maxPendingZaps = 512
486 487 func (z *ZapServer) remember(p *pendingZap) error {
488 z.mu.Lock()
489 if _, exists := z.state.Pending[p.PaymentHash]; !exists && len(z.state.Pending) >= maxPendingZaps {
490 z.mu.Unlock()
491 return fmt.Errorf("too many unpaid zaps pending (%d)", maxPendingZaps)
492 }
493 z.state.Pending[p.PaymentHash] = p
494 z.mu.Unlock()
495 return z.save()
496 }
497 498 func (z *ZapServer) pendingList() []*pendingZap {
499 z.mu.Lock()
500 defer z.mu.Unlock()
501 out := make([]*pendingZap, 0, len(z.state.Pending))
502 for _, p := range z.state.Pending {
503 out = append(out, p)
504 }
505 sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.Before(out[j].CreatedAt) })
506 return out
507 }
508 509 func (z *ZapServer) alreadyReceipted(paymentHash string) bool {
510 z.mu.Lock()
511 defer z.mu.Unlock()
512 _, ok := z.state.Receipts[paymentHash]
513 return ok
514 }
515 516 // hasPending reports whether a zap with this payment hash is still awaiting a
517 // receipt.
518 func (z *ZapServer) hasPending(paymentHash string) bool {
519 z.mu.Lock()
520 defer z.mu.Unlock()
521 _, ok := z.state.Pending[paymentHash]
522 return ok
523 }
524 525 // pending returns a copy of the pending zap for a payment hash, or nil.
526 func (z *ZapServer) pending(paymentHash string) *pendingZap {
527 z.mu.Lock()
528 defer z.mu.Unlock()
529 p, ok := z.state.Pending[paymentHash]
530 if !ok {
531 return nil
532 }
533 cp := *p
534 return &cp
535 }
536 537 // jsonUnmarshalStrict decodes JSON rejecting nothing extra; it exists so the
538 // watcher and the callback parse zap requests identically.
539 func jsonUnmarshalStrict(raw string, v interface{}) error {
540 dec := json.NewDecoder(strings.NewReader(raw))
541 dec.UseNumber()
542 return dec.Decode(v)
543 }
544 545 func (z *ZapServer) markReceipted(paymentHash, eventID string) error {
546 z.mu.Lock()
547 delete(z.state.Pending, paymentHash)
548 z.state.Receipts[paymentHash] = eventID
549 z.mu.Unlock()
550 return z.save()
551 }
552 553 func (z *ZapServer) forget(paymentHash string) error {
554 z.mu.Lock()
555 delete(z.state.Pending, paymentHash)
556 z.mu.Unlock()
557 return z.save()
558 }
559 560 // buildReceipt constructs the kind 9735 event for a settled zap. Content stays
561 // empty and created_at is the paid-at time so the receipt is idempotent
562 // (NIP-57 Appendix E).
563 func (z *ZapServer) buildReceipt(zr *ZapRequest, rawZapRequest, invoice, preimage string, paidAt time.Time) (*nostr.Event, error) {
564 ev := nostr.Event{
565 Kind: zapReceiptKind,
566 CreatedAt: nostr.Timestamp(paidAt.Unix()),
567 Content: "",
568 Tags: nostr.Tags{},
569 }
570 571 // Carry over the p/e/a tags from the zap request.
572 for _, t := range zr.Tags {
573 if len(t) == 0 {
574 continue
575 }
576 switch t[0] {
577 case "p", "e", "a":
578 ev.Tags = append(ev.Tags, nostr.Tag(t))
579 }
580 }
581 // P is the pubkey of the zap sender.
582 ev.Tags = append(ev.Tags, nostr.Tag{"P", zr.PubKey})
583 ev.Tags = append(ev.Tags, nostr.Tag{"bolt11", invoice})
584 ev.Tags = append(ev.Tags, nostr.Tag{"description", rawZapRequest})
585 if preimage != "" {
586 ev.Tags = append(ev.Tags, nostr.Tag{"preimage", preimage})
587 }
588 589 if err := ev.Sign(z.secret); err != nil {
590 return nil, fmt.Errorf("sign receipt: %w", err)
591 }
592 return &ev, nil
593 }
594 595 // publishReceipt sends the receipt to the relays named in the zap request. It
596 // succeeds if at least one relay accepts it; relays are independent.
597 func publishReceipt(ctx context.Context, ev *nostr.Event, relays []string) error {
598 var (
599 okCount int
600 lastErr error
601 )
602 for _, r := range relays {
603 relayCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
604 relay, err := nostr.RelayConnect(relayCtx, r)
605 if err != nil {
606 cancel()
607 lastErr = err
608 log.Printf("zap receipt: cannot connect to %s: %v", r, err)
609 continue
610 }
611 err = relay.Publish(relayCtx, *ev)
612 cancel()
613 relay.Close()
614 if err != nil {
615 lastErr = err
616 log.Printf("zap receipt: publish to %s failed: %v", r, err)
617 continue
618 }
619 okCount++
620 }
621 if okCount == 0 {
622 if lastErr == nil {
623 lastErr = fmt.Errorf("no relays available")
624 }
625 return fmt.Errorf("receipt published to 0/%d relays: %w", len(relays), lastErr)
626 }
627 log.Printf("zap receipt %s published to %d/%d relays", ev.ID, okCount, len(relays))
628 return nil
629 }
630