// Package lightning verifies the Lightning leg of a musiquay purchase. // // A NIP-57 zap receipt (kind 9735) is an attestation by whichever provider // published it, so it is not trust by itself. The verifier accepts a receipt // only from a configured provider allowlist, and optionally asks that provider's // LNURL verify endpoint. It also parses the embedded zap request (kind 9734) to // check the asset, the seller, the amount, and the buyer's signature. package lightning import ( "context" "encoding/json" "fmt" "net/http" "strconv" "strings" "time" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/hex" "git.smesh.lol/orly/pkg/nostr/encoders/tag" ) // Kinds used by NIP-57. const ( ZapRequestKind = 9734 ZapReceiptKind = 9735 ) // Provider is an LNURL server allowed to attest a zap. type Provider struct { // Pubkey is the hex key that signs the kind 9735 receipt. Pubkey string // Name is for logs. Name string } // Config wires a verifier. type Config struct { // Providers is the allowlist. Empty refuses every receipt. Providers []Provider // VerifyURL, when non-nil, returns the provider's verify endpoint for a // receipt. A deployment that has one should use it in addition to the // allowlist. VerifyURL func(receipt *event.E) (string, bool) // Client is optional. Client *http.Client // Now overrides the clock. Now func() time.Time } // Verifier checks zap receipts. type Verifier struct { cfg Config client *http.Client } // New creates a verifier. func New(cfg Config) *Verifier { client := cfg.Client if client == nil { client = &http.Client{Timeout: 15 * time.Second} } return &Verifier{cfg: cfg, client: client} } // Claim is the verified content of a receipt. type Claim struct { // Buyer is the zap request author. Buyer []byte // Provider is the receipt signer. Provider []byte // AssetAddress is the a tag the buyer paid for. AssetAddress string // Sats is the amount in satoshis. Sats int64 // ReceiptID and RequestID are provenance. ReceiptID string RequestID string } // Verify checks a 9735 receipt for one order. // // assetAddress is the coordinate the order names, seller is the payee, and // priceSats is the net price that must be covered. func (v *Verifier) Verify(ctx context.Context, receipt *event.E, assetAddress string, seller []byte, priceSats int64) (*Claim, error) { if receipt == nil { return nil, fmt.Errorf("lightning: nil receipt") } if receipt.Kind != ZapReceiptKind { return nil, fmt.Errorf("lightning: kind %d is not a zap receipt", receipt.Kind) } if valid, err := receipt.Verify(); err != nil || !valid { return nil, fmt.Errorf("lightning: receipt signature is invalid") } if len(v.cfg.Providers) == 0 { return nil, fmt.Errorf("lightning: no provider allowlist is configured") } allowed := false for _, p := range v.cfg.Providers { if equalHex(p.Pubkey, receipt.Pubkey) { allowed = true break } } if !allowed { return nil, fmt.Errorf("lightning: receipt signer %s is not an allowed provider", hex.Enc(receipt.Pubkey)) } // The receipt's p tag is the payee. pTags := receipt.Tags.GetAll([]byte("p")) if !hasPubkey(pTags, seller) { return nil, fmt.Errorf("lightning: receipt is not paid to this seller") } desc := tagValue(receipt, "description") if desc == "" { return nil, fmt.Errorf("lightning: receipt has no zap request") } req := event.New() if err := json.Unmarshal([]byte(desc), req); err != nil { return nil, fmt.Errorf("lightning: decode zap request: %w", err) } if req.Kind != ZapRequestKind { return nil, fmt.Errorf("lightning: embedded event is not a zap request") } if valid, err := req.Verify(); err != nil || !valid { return nil, fmt.Errorf("lightning: zap request signature is invalid") } if got := tagValue(req, "a"); got != assetAddress { return nil, fmt.Errorf("lightning: zap is for %q, order is for %q", got, assetAddress) } if !hasPubkey(req.Tags.GetAll([]byte("p")), seller) { return nil, fmt.Errorf("lightning: zap request does not name this seller") } msat, err := strconv.ParseInt(tagValue(req, "amount"), 10, 64) if err != nil || msat <= 0 { return nil, fmt.Errorf("lightning: zap request has no valid amount") } sats := msat / 1000 if sats < priceSats { return nil, fmt.Errorf("lightning: zap is %d sats, price is %d", sats, priceSats) } // Optional online verification through the provider's LNURL endpoint. if v.cfg.VerifyURL != nil { if u, ok := v.cfg.VerifyURL(receipt); ok && u != "" { if err := v.verifyURL(ctx, u); err != nil { return nil, err } } } return &Claim{ Buyer: append([]byte(nil), req.Pubkey...), Provider: append([]byte(nil), receipt.Pubkey...), AssetAddress: assetAddress, Sats: sats, ReceiptID: hex.Enc(receipt.ID), RequestID: hex.Enc(req.ID), }, nil } // verifyURL checks a standard LNURL verify response. func (v *Verifier) verifyURL(ctx context.Context, u string) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return err } resp, err := v.client.Do(req) if err != nil { return fmt.Errorf("lightning: verify endpoint: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("lightning: verify endpoint status %d", resp.StatusCode) } var out struct { Status string `json:"status"` Settled bool `json:"settled"` } if err = json.NewDecoder(resp.Body).Decode(&out); err != nil { return fmt.Errorf("lightning: verify response: %w", err) } if out.Status != "OK" || !out.Settled { return fmt.Errorf("lightning: payment is not settled") } return nil } // VerifyOption is a convenience for the sales service: it composes the order's // asset and price into the call. type OrderView interface { AssetAddress() string SellerPubkey() []byte PriceSats() int64 } // VerifyOrder adapts Verify to an order view. func (v *Verifier) VerifyOrder(ctx context.Context, receipt *event.E, o OrderView) (*Claim, error) { return v.Verify(ctx, receipt, o.AssetAddress(), o.SellerPubkey(), o.PriceSats()) } func equalHex(a string, b []byte) bool { if len(b) != 32 { return false } return strings.EqualFold(a, hex.Enc(b)) } func hasPubkey(tags []*tag.T, want []byte) bool { for _, t := range tags { if equalHex(string(t.ValueHex()), want) { return true } } return false } func tagValue(ev *event.E, name string) string { if ev == nil || ev.Tags == nil { return "" } t := ev.Tags.GetFirst([]byte(name)) if t == nil { return "" } return string(t.Value()) }