orders.go raw

   1  // Package orders decodes and validates musiquay purchase orders (kind 3222).
   2  //
   3  // An order is a rumor carried in a NIP-59 gift wrap. It names the asset
   4  // coordinate, the tier, the price the buyer understood, and the payment. The
   5  // sales service validates it in a fixed order before touching the entitlement
   6  // set: seal author, asset author, price, mint, amount, and settlement.
   7  package orders
   8  
   9  import (
  10  	"encoding/hex"
  11  	"fmt"
  12  	"strconv"
  13  	"strings"
  14  	"time"
  15  
  16  	"git.smesh.lol/orly/pkg/musiquay/deed"
  17  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
  18  	"git.smesh.lol/orly/pkg/nostr/encoders/kind"
  19  )
  20  
  21  // Payment methods.
  22  const (
  23  	PaymentCashu     = "cashu"
  24  	PaymentLightning = "lightning"
  25  )
  26  
  27  // Order is a parsed 3222 rumor.
  28  type Order struct {
  29  	Event *event.E
  30  	// Buyer is the rumor author.
  31  	Buyer []byte
  32  	// Seller is the p tag, when present.
  33  	Seller []byte
  34  	// Coordinate is the asset coordinate "kind:pubkey:d".
  35  	Coordinate string
  36  	// AssetID is the optional explicit asset tag.
  37  	AssetID string
  38  	// Tier is fan, retail, or sub.
  39  	Tier deed.Tier
  40  	// Channel and Period apply to sub orders.
  41  	Channel string
  42  	Period  int64
  43  	// PriceSats is the net price the buyer agreed to.
  44  	PriceSats int64
  45  	// Payment is "cashu" or "lightning".
  46  	Payment string
  47  	// Mint and Token apply to a Cashu payment.
  48  	Mint  string
  49  	Token string
  50  	// ZapReceipt is the 9735 event id for a Lightning payment.
  51  	ZapReceipt string
  52  }
  53  
  54  // ParseOrder structurally validates a 3222 rumor. It does not check the asset
  55  // or the payment.
  56  func ParseOrder(ev *event.E) (*Order, error) {
  57  	if ev == nil {
  58  		return nil, fmt.Errorf("orders: nil order")
  59  	}
  60  	if ev.Kind != kind.PurchaseOrder.ToU16() {
  61  		return nil, fmt.Errorf("orders: kind %d is not a purchase order", ev.Kind)
  62  	}
  63  	if len(ev.Pubkey) != 32 {
  64  		return nil, fmt.Errorf("orders: order has no buyer pubkey")
  65  	}
  66  	o := &Order{
  67  		Event:      ev,
  68  		Buyer:      append([]byte(nil), ev.Pubkey...),
  69  		Coordinate: tagValue(ev, "a"),
  70  		AssetID:    tagValue(ev, deed.TagAsset),
  71  		Tier:       deed.Tier(tagValue(ev, "tier")),
  72  		Channel:    tagValue(ev, "channel"),
  73  		PriceSats:  0,
  74  		Payment:    tagValue(ev, "payment"),
  75  		Mint:       tagValue(ev, "mint"),
  76  		Token:      tagValue(ev, "token"),
  77  		ZapReceipt: tagValue(ev, "zap"),
  78  	}
  79  	if o.Coordinate == "" && o.AssetID == "" {
  80  		return nil, fmt.Errorf("orders: order names no asset")
  81  	}
  82  	if o.AssetID != "" && !deed.IsAssetID(o.AssetID) {
  83  		return nil, fmt.Errorf("orders: order asset id is invalid")
  84  	}
  85  	switch o.Tier {
  86  	case deed.TierFan, deed.TierRetail:
  87  		if o.Coordinate == "" {
  88  			// A fan/retail order must name the coordinate it saw, so the seller
  89  			// can check the price against what was offered.
  90  			return nil, fmt.Errorf("orders: %s order has no coordinate", o.Tier)
  91  		}
  92  	case deed.TierSub:
  93  		if o.Channel == "" {
  94  			return nil, fmt.Errorf("orders: sub order has no channel")
  95  		}
  96  	default:
  97  		return nil, fmt.Errorf("orders: unrecognized tier %q", o.Tier)
  98  	}
  99  	if price := tagValue(ev, "price"); price != "" {
 100  		n, err := strconv.ParseInt(price, 10, 64)
 101  		if err != nil || n < 0 {
 102  			return nil, fmt.Errorf("orders: order price %q is invalid", price)
 103  		}
 104  		o.PriceSats = n
 105  	}
 106  	if period := tagValue(ev, "period"); period != "" {
 107  		n, err := strconv.ParseInt(period, 10, 64)
 108  		if err != nil || n < 0 {
 109  			return nil, fmt.Errorf("orders: order period %q is invalid", period)
 110  		}
 111  		o.Period = n
 112  	}
 113  	if p := ev.Tags.GetFirst([]byte("p")); p != nil {
 114  		raw, err := hex.DecodeString(string(p.ValueHex()))
 115  		if err != nil || len(raw) != 32 {
 116  			return nil, fmt.Errorf("orders: order seller tag is invalid")
 117  		}
 118  		o.Seller = raw
 119  	}
 120  	return o, nil
 121  }
 122  
 123  // AssetView is what the seller knows about the asset at validation time.
 124  type AssetView struct {
 125  	AssetID      string
 126  	Coordinate   string
 127  	SourceEvent  string
 128  	Owner        []byte
 129  	PriceSats    int64
 130  	Mints        []string
 131  	Retailers    [][]byte
 132  	ChannelMatch bool
 133  }
 134  
 135  // CheckOptions supplies the facts an order is checked against.
 136  type CheckOptions struct {
 137  	// Asset is the resolved asset the order names.
 138  	Asset *AssetView
 139  	// Seller is this service's pubkey. When the order names a seller, it must
 140  	// be this key.
 141  	Seller []byte
 142  	// Now overrides the clock.
 143  	Now time.Time
 144  	// MaxAge rejects a stale order; zero means 24 hours.
 145  	MaxAge time.Duration
 146  	// AcceptLightning enables the Lightning leg. The caller must have already
 147  	// verified the zap receipt.
 148  	AcceptLightning bool
 149  }
 150  
 151  // Check validates the order against the asset and this seller.
 152  //
 153  // The checks run in the order the specification requires: identity, asset,
 154  // price, payment method, mint, and presence of the proof. Settlement (the swap)
 155  // is the caller's next step and is not performed here.
 156  func (o *Order) Check(opts CheckOptions) error {
 157  	if opts.Asset == nil {
 158  		return fmt.Errorf("orders: asset is unknown")
 159  	}
 160  	if !deed.IsAssetID(opts.Asset.AssetID) {
 161  		return fmt.Errorf("orders: resolved asset id is invalid")
 162  	}
 163  	if o.AssetID != "" && o.AssetID != opts.Asset.AssetID {
 164  		return fmt.Errorf("orders: order names asset %s, resolved %s", o.AssetID, opts.Asset.AssetID)
 165  	}
 166  	if o.Coordinate != "" && opts.Asset.Coordinate != "" && o.Coordinate != opts.Asset.Coordinate {
 167  		return fmt.Errorf("orders: order names coordinate %s, asset is at %s", o.Coordinate, opts.Asset.Coordinate)
 168  	}
 169  	if len(opts.Seller) == 32 && len(o.Seller) == 32 {
 170  		if !equalBytes(o.Seller, opts.Seller) {
 171  			return fmt.Errorf("orders: order is addressed to another seller")
 172  		}
 173  	}
 174  
 175  	now := opts.Now
 176  	if now.IsZero() {
 177  		now = time.Now()
 178  	}
 179  	maxAge := opts.MaxAge
 180  	if maxAge <= 0 {
 181  		maxAge = 24 * time.Hour
 182  	}
 183  	if o.Event.CreatedAt > now.Add(5*time.Minute).Unix() {
 184  		return fmt.Errorf("orders: order created_at is in the future")
 185  	}
 186  	if o.Event.CreatedAt < now.Add(-maxAge).Unix() {
 187  		return fmt.Errorf("orders: order is stale")
 188  	}
 189  
 190  	if o.PriceSats < opts.Asset.PriceSats {
 191  		return fmt.Errorf("orders: price %d is below the asset price %d", o.PriceSats, opts.Asset.PriceSats)
 192  	}
 193  
 194  	switch o.Payment {
 195  	case PaymentCashu:
 196  		if o.Token == "" {
 197  			return fmt.Errorf("orders: cashu order has no token")
 198  		}
 199  		if o.Mint == "" {
 200  			return fmt.Errorf("orders: cashu order has no mint")
 201  		}
 202  		if len(opts.Asset.Mints) > 0 && !containsFold(opts.Asset.Mints, o.Mint) {
 203  			return fmt.Errorf("orders: mint %s is not accepted for this asset", o.Mint)
 204  		}
 205  	case PaymentLightning:
 206  		if !opts.AcceptLightning {
 207  			return fmt.Errorf("orders: lightning payment is not enabled")
 208  		}
 209  		if o.ZapReceipt == "" {
 210  			return fmt.Errorf("orders: lightning order has no zap receipt")
 211  		}
 212  	case "":
 213  		return fmt.Errorf("orders: order has no payment method")
 214  	default:
 215  		return fmt.Errorf("orders: unsupported payment method %q", o.Payment)
 216  	}
 217  
 218  	if o.Tier == deed.TierSub {
 219  		if o.Period <= 0 {
 220  			return fmt.Errorf("orders: sub order has no period")
 221  		}
 222  		if !opts.Asset.ChannelMatch {
 223  			return fmt.Errorf("orders: asset is not in the subscribed channel")
 224  		}
 225  	}
 226  	return nil
 227  }
 228  
 229  // RequiredGross returns the token value the buyer must supply: the net price
 230  // plus the mint input fee, which the buyer covers.
 231  func (o *Order) RequiredGross(inputFee uint64) uint64 {
 232  	if o.PriceSats < 0 {
 233  		return 0
 234  	}
 235  	return uint64(o.PriceSats) + inputFee
 236  }
 237  
 238  // ExpiryFor returns the deed expiry for a subscription order.
 239  func (o *Order) ExpiryFor(now time.Time) int64 {
 240  	if o.Tier != deed.TierSub || o.Period <= 0 {
 241  		return 0
 242  	}
 243  	return now.Add(time.Duration(o.Period) * time.Second).Unix()
 244  }
 245  
 246  func tagValue(ev *event.E, name string) string {
 247  	if ev == nil || ev.Tags == nil {
 248  		return ""
 249  	}
 250  	t := ev.Tags.GetFirst([]byte(name))
 251  	if t == nil {
 252  		return ""
 253  	}
 254  	return string(t.Value())
 255  }
 256  
 257  func containsFold(list []string, s string) bool {
 258  	for _, v := range list {
 259  		if strings.EqualFold(strings.TrimRight(v, "/"), strings.TrimRight(s, "/")) {
 260  			return true
 261  		}
 262  	}
 263  	return false
 264  }
 265  
 266  func equalBytes(a, b []byte) bool {
 267  	if len(a) != len(b) {
 268  		return false
 269  	}
 270  	var v byte
 271  	for i := range a {
 272  		v |= a[i] ^ b[i]
 273  	}
 274  	return v == 0
 275  }
 276