lightning.go raw

   1  // Package lightning verifies the Lightning leg of a musiquay purchase.
   2  //
   3  // A NIP-57 zap receipt (kind 9735) is an attestation by whichever provider
   4  // published it, so it is not trust by itself. The verifier accepts a receipt
   5  // only from a configured provider allowlist, and optionally asks that provider's
   6  // LNURL verify endpoint. It also parses the embedded zap request (kind 9734) to
   7  // check the asset, the seller, the amount, and the buyer's signature.
   8  package lightning
   9  
  10  import (
  11  	"context"
  12  	"encoding/json"
  13  	"fmt"
  14  	"net/http"
  15  	"strconv"
  16  	"strings"
  17  	"time"
  18  
  19  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
  20  	"git.smesh.lol/orly/pkg/nostr/encoders/hex"
  21  	"git.smesh.lol/orly/pkg/nostr/encoders/tag"
  22  )
  23  
  24  // Kinds used by NIP-57.
  25  const (
  26  	ZapRequestKind = 9734
  27  	ZapReceiptKind = 9735
  28  )
  29  
  30  // Provider is an LNURL server allowed to attest a zap.
  31  type Provider struct {
  32  	// Pubkey is the hex key that signs the kind 9735 receipt.
  33  	Pubkey string
  34  	// Name is for logs.
  35  	Name string
  36  }
  37  
  38  // Config wires a verifier.
  39  type Config struct {
  40  	// Providers is the allowlist. Empty refuses every receipt.
  41  	Providers []Provider
  42  	// VerifyURL, when non-nil, returns the provider's verify endpoint for a
  43  	// receipt. A deployment that has one should use it in addition to the
  44  	// allowlist.
  45  	VerifyURL func(receipt *event.E) (string, bool)
  46  	// Client is optional.
  47  	Client *http.Client
  48  	// Now overrides the clock.
  49  	Now func() time.Time
  50  }
  51  
  52  // Verifier checks zap receipts.
  53  type Verifier struct {
  54  	cfg    Config
  55  	client *http.Client
  56  }
  57  
  58  // New creates a verifier.
  59  func New(cfg Config) *Verifier {
  60  	client := cfg.Client
  61  	if client == nil {
  62  		client = &http.Client{Timeout: 15 * time.Second}
  63  	}
  64  	return &Verifier{cfg: cfg, client: client}
  65  }
  66  
  67  // Claim is the verified content of a receipt.
  68  type Claim struct {
  69  	// Buyer is the zap request author.
  70  	Buyer []byte
  71  	// Provider is the receipt signer.
  72  	Provider []byte
  73  	// AssetAddress is the a tag the buyer paid for.
  74  	AssetAddress string
  75  	// Sats is the amount in satoshis.
  76  	Sats int64
  77  	// ReceiptID and RequestID are provenance.
  78  	ReceiptID string
  79  	RequestID string
  80  }
  81  
  82  // Verify checks a 9735 receipt for one order.
  83  //
  84  // assetAddress is the coordinate the order names, seller is the payee, and
  85  // priceSats is the net price that must be covered.
  86  func (v *Verifier) Verify(ctx context.Context, receipt *event.E, assetAddress string, seller []byte, priceSats int64) (*Claim, error) {
  87  	if receipt == nil {
  88  		return nil, fmt.Errorf("lightning: nil receipt")
  89  	}
  90  	if receipt.Kind != ZapReceiptKind {
  91  		return nil, fmt.Errorf("lightning: kind %d is not a zap receipt", receipt.Kind)
  92  	}
  93  	if valid, err := receipt.Verify(); err != nil || !valid {
  94  		return nil, fmt.Errorf("lightning: receipt signature is invalid")
  95  	}
  96  	if len(v.cfg.Providers) == 0 {
  97  		return nil, fmt.Errorf("lightning: no provider allowlist is configured")
  98  	}
  99  	allowed := false
 100  	for _, p := range v.cfg.Providers {
 101  		if equalHex(p.Pubkey, receipt.Pubkey) {
 102  			allowed = true
 103  			break
 104  		}
 105  	}
 106  	if !allowed {
 107  		return nil, fmt.Errorf("lightning: receipt signer %s is not an allowed provider", hex.Enc(receipt.Pubkey))
 108  	}
 109  
 110  	// The receipt's p tag is the payee.
 111  	pTags := receipt.Tags.GetAll([]byte("p"))
 112  	if !hasPubkey(pTags, seller) {
 113  		return nil, fmt.Errorf("lightning: receipt is not paid to this seller")
 114  	}
 115  
 116  	desc := tagValue(receipt, "description")
 117  	if desc == "" {
 118  		return nil, fmt.Errorf("lightning: receipt has no zap request")
 119  	}
 120  	req := event.New()
 121  	if err := json.Unmarshal([]byte(desc), req); err != nil {
 122  		return nil, fmt.Errorf("lightning: decode zap request: %w", err)
 123  	}
 124  	if req.Kind != ZapRequestKind {
 125  		return nil, fmt.Errorf("lightning: embedded event is not a zap request")
 126  	}
 127  	if valid, err := req.Verify(); err != nil || !valid {
 128  		return nil, fmt.Errorf("lightning: zap request signature is invalid")
 129  	}
 130  
 131  	if got := tagValue(req, "a"); got != assetAddress {
 132  		return nil, fmt.Errorf("lightning: zap is for %q, order is for %q", got, assetAddress)
 133  	}
 134  	if !hasPubkey(req.Tags.GetAll([]byte("p")), seller) {
 135  		return nil, fmt.Errorf("lightning: zap request does not name this seller")
 136  	}
 137  	msat, err := strconv.ParseInt(tagValue(req, "amount"), 10, 64)
 138  	if err != nil || msat <= 0 {
 139  		return nil, fmt.Errorf("lightning: zap request has no valid amount")
 140  	}
 141  	sats := msat / 1000
 142  	if sats < priceSats {
 143  		return nil, fmt.Errorf("lightning: zap is %d sats, price is %d", sats, priceSats)
 144  	}
 145  
 146  	// Optional online verification through the provider's LNURL endpoint.
 147  	if v.cfg.VerifyURL != nil {
 148  		if u, ok := v.cfg.VerifyURL(receipt); ok && u != "" {
 149  			if err := v.verifyURL(ctx, u); err != nil {
 150  				return nil, err
 151  			}
 152  		}
 153  	}
 154  
 155  	return &Claim{
 156  		Buyer:        append([]byte(nil), req.Pubkey...),
 157  		Provider:     append([]byte(nil), receipt.Pubkey...),
 158  		AssetAddress: assetAddress,
 159  		Sats:         sats,
 160  		ReceiptID:    hex.Enc(receipt.ID),
 161  		RequestID:    hex.Enc(req.ID),
 162  	}, nil
 163  }
 164  
 165  // verifyURL checks a standard LNURL verify response.
 166  func (v *Verifier) verifyURL(ctx context.Context, u string) error {
 167  	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
 168  	if err != nil {
 169  		return err
 170  	}
 171  	resp, err := v.client.Do(req)
 172  	if err != nil {
 173  		return fmt.Errorf("lightning: verify endpoint: %w", err)
 174  	}
 175  	defer resp.Body.Close()
 176  	if resp.StatusCode != http.StatusOK {
 177  		return fmt.Errorf("lightning: verify endpoint status %d", resp.StatusCode)
 178  	}
 179  	var out struct {
 180  		Status  string `json:"status"`
 181  		Settled bool   `json:"settled"`
 182  	}
 183  	if err = json.NewDecoder(resp.Body).Decode(&out); err != nil {
 184  		return fmt.Errorf("lightning: verify response: %w", err)
 185  	}
 186  	if out.Status != "OK" || !out.Settled {
 187  		return fmt.Errorf("lightning: payment is not settled")
 188  	}
 189  	return nil
 190  }
 191  
 192  // VerifyOption is a convenience for the sales service: it composes the order's
 193  // asset and price into the call.
 194  type OrderView interface {
 195  	AssetAddress() string
 196  	SellerPubkey() []byte
 197  	PriceSats() int64
 198  }
 199  
 200  // VerifyOrder adapts Verify to an order view.
 201  func (v *Verifier) VerifyOrder(ctx context.Context, receipt *event.E, o OrderView) (*Claim, error) {
 202  	return v.Verify(ctx, receipt, o.AssetAddress(), o.SellerPubkey(), o.PriceSats())
 203  }
 204  
 205  func equalHex(a string, b []byte) bool {
 206  	if len(b) != 32 {
 207  		return false
 208  	}
 209  	return strings.EqualFold(a, hex.Enc(b))
 210  }
 211  
 212  func hasPubkey(tags []*tag.T, want []byte) bool {
 213  	for _, t := range tags {
 214  		if equalHex(string(t.ValueHex()), want) {
 215  			return true
 216  		}
 217  	}
 218  	return false
 219  }
 220  
 221  func tagValue(ev *event.E, name string) string {
 222  	if ev == nil || ev.Tags == nil {
 223  		return ""
 224  	}
 225  	t := ev.Tags.GetFirst([]byte(name))
 226  	if t == nil {
 227  		return ""
 228  	}
 229  	return string(t.Value())
 230  }
 231