package main // NIP-57 Lightning zaps. // // The flow implemented here (NIP-57 steps 1-8): // // 1. The payRequest response advertises allowsNostr + nostrPubkey. // 2. A client sends a signed kind 9734 zap request to the callback as the // `nostr` query parameter. // 3. The callback validates it and asks the wallet for an invoice whose // description_hash is sha256 of the zap request note and nothing else. // 4. The zap request is persisted against the invoice payment hash. // 5. When the invoice settles, THIS SERVER (not the wallet) publishes a kind // 9735 receipt to the relays named in the zap request, signed with the key // advertised as nostrPubkey. // // Step 5 is server-side by definition: the wallet only ever sees an opaque // description hash, so it cannot construct a receipt. import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "log" "os" "path/filepath" "sort" "strings" "sync" "time" "github.com/nbd-wtf/go-nostr" ) const ( zapRequestKind = 9734 zapReceiptKind = 9735 // bolt11TagPaymentHash is the raw 5-bit value of the 'p' tag type // ('p' = 1 in the bech32 charset), and a 32-byte value occupies 52 groups. bolt11TagPaymentHash = 1 bolt11PaymentHashGroups = 52 ) // deriveKey deterministically derives a 32-byte secret key from a base secret and // a domain-separation label, so the receipt identity survives restarts without // requiring a separate secret to be provisioned. func deriveKey(label, base string) string { h := sha256.Sum256([]byte(label + "\x00" + base)) return hex.EncodeToString(h[:]) } // ZapRequest is the subset of a kind 9734 event this server needs. Tags are // kept raw so the exact received bytes can be hashed for the description hash. type ZapRequest struct { ID string `json:"id"` PubKey string `json:"pubkey"` CreatedAt int64 `json:"created_at"` Kind int `json:"kind"` Tags [][]string `json:"tags"` Content string `json:"content"` Sig string `json:"sig"` } // validateZapRequest performs the Appendix D checks. It returns the relays to // publish the receipt to. func validateZapRequest(zr *ZapRequest, amountMsat uint64, callbackHost string) (relays []string, err error) { if zr.Kind != zapRequestKind { return nil, fmt.Errorf("zap request kind is %d, want %d", zr.Kind, zapRequestKind) } if len(zr.ID) != 64 || len(zr.PubKey) != 64 || len(zr.Sig) != 128 { return nil, fmt.Errorf("zap request has malformed id/pubkey/sig") } if len(zr.Tags) == 0 { return nil, fmt.Errorf("zap request has no tags") } var ( pTags []string eTags int pUpper []string amountTag string hasAmount bool ) for _, t := range zr.Tags { if len(t) == 0 { continue } switch t[0] { case "relays": for _, r := range t[1:] { if strings.HasPrefix(r, "wss://") || strings.HasPrefix(r, "ws://") { relays = append(relays, r) } } case "p": if len(t) >= 2 { pTags = append(pTags, t[1]) } case "P": if len(t) >= 2 { pUpper = append(pUpper, t[1]) } case "e": eTags++ case "amount": if len(t) >= 2 { amountTag = t[1] hasAmount = true } } } // NIP-57 Appendix D.3 if len(pTags) != 1 { return nil, fmt.Errorf("zap request must have exactly one p tag, has %d", len(pTags)) } // D.4 if eTags > 1 { return nil, fmt.Errorf("zap request must have at most one e tag, has %d", eTags) } // D.5 if len(relays) == 0 { return nil, fmt.Errorf("zap request has no usable relays tag") } // D.6 if hasAmount && amountTag != fmt.Sprintf("%d", amountMsat) { return nil, fmt.Errorf("zap request amount tag %q does not match amount %d", amountTag, amountMsat) } // D.8 if len(pUpper) > 1 { return nil, fmt.Errorf("zap request must have at most one P tag, has %d", len(pUpper)) } // D.1 - the signature must actually verify, otherwise anyone could mint // receipts by fabricating zap requests. tags := make(nostr.Tags, 0, len(zr.Tags)) for _, t := range zr.Tags { tags = append(tags, nostr.Tag(t)) } ev := nostr.Event{ ID: zr.ID, PubKey: zr.PubKey, CreatedAt: nostr.Timestamp(zr.CreatedAt), Kind: zapRequestKind, Tags: tags, Content: zr.Content, Sig: zr.Sig, } ok, verr := ev.CheckSignature() if verr != nil { return nil, fmt.Errorf("zap request signature is invalid: %w", verr) } if !ok { return nil, fmt.Errorf("zap request signature is invalid") } // CheckSignature only ties sig -> id -> pubkey; it does NOT check that the id // is the hash of the event content. The id is what the invoice description // hash commits to (via the canonical re-serialisation), so a mismatched id // must be rejected or a client could have the receipt commit to a bogus id. if ev.GetID() != zr.ID { return nil, fmt.Errorf("zap request id does not match its content") } // Reject requests that are not for this endpoint, when an lnurl tag is // present (D-recommended). Cheap sanity check, no bech32 needed. for _, t := range zr.Tags { if len(t) >= 2 && t[0] == "lnurl" { if !strings.HasPrefix(strings.ToLower(t[1]), "lnurl1") { return nil, fmt.Errorf("zap request lnurl tag is not an lnurl") } } } // Bound clock skew so a stale or far-future request cannot be replayed. now := time.Now().Unix() if zr.CreatedAt < now-3600 || zr.CreatedAt > now+600 { return nil, fmt.Errorf("zap request created_at %d is not recent", zr.CreatedAt) } // Deduplicate and cap the relay list we will publish to. seen := map[string]bool{} uniq := relays[:0] for _, r := range relays { if !seen[r] { seen[r] = true uniq = append(uniq, r) } } if len(uniq) > 16 { uniq = uniq[:16] } return uniq, nil } // parseAndValidateZap decodes the `nostr` query parameter into a ZapRequest and // applies the NIP-57 Appendix D checks. // // It returns the CANONICAL serialization of the validated event rather than the // raw query bytes. The event id and signature only commit to the canonical // encoding, so hashing arbitrary client-supplied bytes would let a client commit // the invoice (and therefore the receipt) to text that no valid zap request // verifies against. func parseAndValidateZap(raw string, amountMsat uint64) (*ZapRequest, string, []string, error) { var zr ZapRequest dec := json.NewDecoder(strings.NewReader(raw)) dec.UseNumber() if err := dec.Decode(&zr); err != nil { return nil, "", nil, fmt.Errorf("zap request is not valid JSON: %w", err) } relays, err := validateZapRequest(&zr, amountMsat, "") if err != nil { return nil, "", nil, err } return &zr, canonicalZapRequest(&zr), relays, nil } // canonicalZapRequest rebuilds the exact JSON encoding the event id and // signature are computed over, so hashing it is equivalent to hashing the // verified event. func canonicalZapRequest(zr *ZapRequest) string { return zapEvent(zr).String() } // zapEvent converts a parsed zap request back into a nostr event. func zapEvent(zr *ZapRequest) *nostr.Event { tags := make(nostr.Tags, 0, len(zr.Tags)) for _, t := range zr.Tags { tags = append(tags, nostr.Tag(t)) } return &nostr.Event{ ID: zr.ID, PubKey: zr.PubKey, CreatedAt: nostr.Timestamp(zr.CreatedAt), Kind: zapRequestKind, Tags: tags, Content: zr.Content, Sig: zr.Sig, } } // --- minimal bolt11 payment-hash extraction --------------------------------- // // A full bolt11 decoder is a large dependency (the available one pulls in lnd, // etcd and docker), but the zap flow needs exactly one field: the payment hash // (`p` tag), which is the SHA256 of the payment preimage and is what // lookup_invoice keys on. This is a self-contained bech32 + tagged-field reader // for that one field, covered by a test against a real invoice. const bech32Charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" // bech32DataPart returns the 5-bit data groups of a bech32 string, excluding the // 6-character checksum. func bech32DataPart(s string) ([]byte, error) { s = strings.ToLower(strings.TrimSpace(s)) pos := strings.LastIndexByte(s, '1') if pos < 1 || pos+7 > len(s) { return nil, fmt.Errorf("not a bech32 string") } out := make([]byte, 0, len(s)-pos-1) for i := pos + 1; i < len(s); i++ { idx := strings.IndexByte(bech32Charset, s[i]) if idx < 0 { return nil, fmt.Errorf("invalid bech32 character %q", s[i]) } out = append(out, byte(idx)) } return out[:len(out)-6], nil } // bitsToBytes repacks 5-bit groups into bytes. pad must be false when the total // bit count is not a multiple of 8, which is the case for a bolt11 data part. func bitsToBytes(values []byte, pad bool) []byte { var ( acc uint32 bits uint out []byte ) for _, v := range values { acc = acc<<5 | uint32(v) bits += 5 for bits >= 8 { bits -= 8 out = append(out, byte(acc>>bits)) } } if pad && bits > 0 { out = append(out, byte(acc<<(8-bits))) } return out } // paymentHashFromInvoice extracts the payment hash (the `p` tagged field) from a // BOLT11 invoice. // // Details of the encoding that are easy to get wrong: // - the bech32 data part excludes the 6 checksum groups but INCLUDES the // trailing 104-group ECDSA signature, which must be dropped before walking // the tagged fields; // - the timestamp is the first 7 groups (35 bits); // - each tagged field is: ONE group of type, TWO groups of length, then // `length` groups of value - the length counts 5-bit groups, not bytes, so a // 32-byte value has length 52. // // Verified against a real invoice by TestPaymentHashFromInvoice. func paymentHashFromInvoice(invoice string) (string, error) { groups, err := bech32DataPart(invoice) if err != nil { return "", err } // Drop the 104-group signature to leave the timestamp and tagged fields. if len(groups) <= 104 { return "", fmt.Errorf("invoice data too short") } data := groups[:len(groups)-104] // 7 groups of 5 bits hold the 35-bit timestamp. const timestampGroups = 7 if len(data) < timestampGroups { return "", fmt.Errorf("invoice too short for a timestamp") } i := timestampGroups for i+3 <= len(data) { tag := data[i] length := int(data[i+1])<<5 | int(data[i+2]) i += 3 if length <= 0 || i+length > len(data) { // Malformed or trailing field; nothing further we can read. break } value := data[i : i+length] i += length if tag == bolt11TagPaymentHash { if length != bolt11PaymentHashGroups { return "", fmt.Errorf("payment hash field has %d groups, want %d", length, bolt11PaymentHashGroups) } raw := bitsToBytes(value, false) if len(raw) != 32 { return "", fmt.Errorf("payment hash decoded to %d bytes, want 32", len(raw)) } return hex.EncodeToString(raw), nil } } return "", fmt.Errorf("invoice has no payment hash tag") } // pendingZap is a zap request awaiting settlement. type pendingZap struct { PaymentHash string `json:"payment_hash"` ZapRequest string `json:"zap_request"` // exact bytes received, for the description tag Relays []string `json:"relays"` AmountMsat uint64 `json:"amount_msat"` Invoice string `json:"invoice"` CreatedAt time.Time `json:"created_at"` } // zapState is the on-disk record of zaps awaiting settlement plus the receipts // already published, so a restart neither loses a zap nor double-publishes one. type zapState struct { Pending map[string]*pendingZap `json:"pending"` Receipts map[string]string `json:"receipts"` // payment hash -> receipt event id } // ZapServer holds the receipt-signing identity and the pending-zap store. type ZapServer struct { secret string pubkey string mu sync.Mutex state zapState path string } // loadOrCreateZapKey returns a stable receipt-signing key. ZAP_SECRET (hex) wins; // otherwise the key is derived deterministically from the NWC secret so restarts // do not change the advertised nostrPubkey (clients reject a receipt whose // pubkey differs from the advertised one). func loadOrCreateZapKey(nwcSecret string) (string, error) { if s := strings.TrimSpace(os.Getenv("ZAP_SECRET")); s != "" { if len(s) != 64 { return "", fmt.Errorf("ZAP_SECRET must be 64 hex characters") } return s, nil } if nwcSecret == "" { return "", fmt.Errorf("no ZAP_SECRET and no NWC secret to derive from") } return deriveKey("lnurl-server/zap-receipt", nwcSecret), nil } func newZapServer(nwcSecret, path string) (*ZapServer, error) { sk, err := loadOrCreateZapKey(nwcSecret) if err != nil { return nil, err } pk, err := nostr.GetPublicKey(sk) if err != nil { return nil, fmt.Errorf("derive zap pubkey: %w", err) } z := &ZapServer{ secret: sk, pubkey: pk, path: path, state: zapState{ Pending: map[string]*pendingZap{}, Receipts: map[string]string{}, }, } if err := z.load(); err != nil { log.Printf("zap state load: %v (starting empty)", err) } return z, nil } func (z *ZapServer) load() error { if z.path == "" { return nil } b, err := os.ReadFile(z.path) if err != nil { if os.IsNotExist(err) { return nil } return err } var st zapState if err := json.Unmarshal(b, &st); err != nil { return err } if st.Pending == nil { st.Pending = map[string]*pendingZap{} } if st.Receipts == nil { st.Receipts = map[string]string{} } z.mu.Lock() z.state = st z.mu.Unlock() return nil } // save persists state atomically (write temp + rename) so a crash mid-write // cannot corrupt the store. func (z *ZapServer) save() error { if z.path == "" { return nil } z.mu.Lock() b, err := json.MarshalIndent(z.state, "", " ") z.mu.Unlock() if err != nil { return err } dir := filepath.Dir(z.path) if err := os.MkdirAll(dir, 0o700); err != nil { return err } tmp, err := os.CreateTemp(dir, ".zaps-*.tmp") if err != nil { return err } defer os.Remove(tmp.Name()) if _, err := tmp.Write(b); err != nil { tmp.Close() return err } if err := tmp.Sync(); err != nil { tmp.Close() return err } if err := tmp.Close(); err != nil { return err } return os.Rename(tmp.Name(), z.path) } // maxPendingZaps bounds how much unpaid-zap state is retained, so a client that // requests invoices without paying cannot grow the store (and the sweep work) // without limit. Entries also expire by age in the watcher. const maxPendingZaps = 512 func (z *ZapServer) remember(p *pendingZap) error { z.mu.Lock() if _, exists := z.state.Pending[p.PaymentHash]; !exists && len(z.state.Pending) >= maxPendingZaps { z.mu.Unlock() return fmt.Errorf("too many unpaid zaps pending (%d)", maxPendingZaps) } z.state.Pending[p.PaymentHash] = p z.mu.Unlock() return z.save() } func (z *ZapServer) pendingList() []*pendingZap { z.mu.Lock() defer z.mu.Unlock() out := make([]*pendingZap, 0, len(z.state.Pending)) for _, p := range z.state.Pending { out = append(out, p) } sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.Before(out[j].CreatedAt) }) return out } func (z *ZapServer) alreadyReceipted(paymentHash string) bool { z.mu.Lock() defer z.mu.Unlock() _, ok := z.state.Receipts[paymentHash] return ok } // hasPending reports whether a zap with this payment hash is still awaiting a // receipt. func (z *ZapServer) hasPending(paymentHash string) bool { z.mu.Lock() defer z.mu.Unlock() _, ok := z.state.Pending[paymentHash] return ok } // pending returns a copy of the pending zap for a payment hash, or nil. func (z *ZapServer) pending(paymentHash string) *pendingZap { z.mu.Lock() defer z.mu.Unlock() p, ok := z.state.Pending[paymentHash] if !ok { return nil } cp := *p return &cp } // jsonUnmarshalStrict decodes JSON rejecting nothing extra; it exists so the // watcher and the callback parse zap requests identically. func jsonUnmarshalStrict(raw string, v interface{}) error { dec := json.NewDecoder(strings.NewReader(raw)) dec.UseNumber() return dec.Decode(v) } func (z *ZapServer) markReceipted(paymentHash, eventID string) error { z.mu.Lock() delete(z.state.Pending, paymentHash) z.state.Receipts[paymentHash] = eventID z.mu.Unlock() return z.save() } func (z *ZapServer) forget(paymentHash string) error { z.mu.Lock() delete(z.state.Pending, paymentHash) z.mu.Unlock() return z.save() } // buildReceipt constructs the kind 9735 event for a settled zap. Content stays // empty and created_at is the paid-at time so the receipt is idempotent // (NIP-57 Appendix E). func (z *ZapServer) buildReceipt(zr *ZapRequest, rawZapRequest, invoice, preimage string, paidAt time.Time) (*nostr.Event, error) { ev := nostr.Event{ Kind: zapReceiptKind, CreatedAt: nostr.Timestamp(paidAt.Unix()), Content: "", Tags: nostr.Tags{}, } // Carry over the p/e/a tags from the zap request. for _, t := range zr.Tags { if len(t) == 0 { continue } switch t[0] { case "p", "e", "a": ev.Tags = append(ev.Tags, nostr.Tag(t)) } } // P is the pubkey of the zap sender. ev.Tags = append(ev.Tags, nostr.Tag{"P", zr.PubKey}) ev.Tags = append(ev.Tags, nostr.Tag{"bolt11", invoice}) ev.Tags = append(ev.Tags, nostr.Tag{"description", rawZapRequest}) if preimage != "" { ev.Tags = append(ev.Tags, nostr.Tag{"preimage", preimage}) } if err := ev.Sign(z.secret); err != nil { return nil, fmt.Errorf("sign receipt: %w", err) } return &ev, nil } // publishReceipt sends the receipt to the relays named in the zap request. It // succeeds if at least one relay accepts it; relays are independent. func publishReceipt(ctx context.Context, ev *nostr.Event, relays []string) error { var ( okCount int lastErr error ) for _, r := range relays { relayCtx, cancel := context.WithTimeout(ctx, 8*time.Second) relay, err := nostr.RelayConnect(relayCtx, r) if err != nil { cancel() lastErr = err log.Printf("zap receipt: cannot connect to %s: %v", r, err) continue } err = relay.Publish(relayCtx, *ev) cancel() relay.Close() if err != nil { lastErr = err log.Printf("zap receipt: publish to %s failed: %v", r, err) continue } okCount++ } if okCount == 0 { if lastErr == nil { lastErr = fmt.Errorf("no relays available") } return fmt.Errorf("receipt published to 0/%d relays: %w", len(relays), lastErr) } log.Printf("zap receipt %s published to %d/%d relays", ev.ID, okCount, len(relays)) return nil }