// Package orders decodes and validates musiquay purchase orders (kind 3222). // // An order is a rumor carried in a NIP-59 gift wrap. It names the asset // coordinate, the tier, the price the buyer understood, and the payment. The // sales service validates it in a fixed order before touching the entitlement // set: seal author, asset author, price, mint, amount, and settlement. package orders import ( "encoding/hex" "fmt" "strconv" "strings" "time" "git.smesh.lol/orly/pkg/musiquay/deed" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/kind" ) // Payment methods. const ( PaymentCashu = "cashu" PaymentLightning = "lightning" ) // Order is a parsed 3222 rumor. type Order struct { Event *event.E // Buyer is the rumor author. Buyer []byte // Seller is the p tag, when present. Seller []byte // Coordinate is the asset coordinate "kind:pubkey:d". Coordinate string // AssetID is the optional explicit asset tag. AssetID string // Tier is fan, retail, or sub. Tier deed.Tier // Channel and Period apply to sub orders. Channel string Period int64 // PriceSats is the net price the buyer agreed to. PriceSats int64 // Payment is "cashu" or "lightning". Payment string // Mint and Token apply to a Cashu payment. Mint string Token string // ZapReceipt is the 9735 event id for a Lightning payment. ZapReceipt string } // ParseOrder structurally validates a 3222 rumor. It does not check the asset // or the payment. func ParseOrder(ev *event.E) (*Order, error) { if ev == nil { return nil, fmt.Errorf("orders: nil order") } if ev.Kind != kind.PurchaseOrder.ToU16() { return nil, fmt.Errorf("orders: kind %d is not a purchase order", ev.Kind) } if len(ev.Pubkey) != 32 { return nil, fmt.Errorf("orders: order has no buyer pubkey") } o := &Order{ Event: ev, Buyer: append([]byte(nil), ev.Pubkey...), Coordinate: tagValue(ev, "a"), AssetID: tagValue(ev, deed.TagAsset), Tier: deed.Tier(tagValue(ev, "tier")), Channel: tagValue(ev, "channel"), PriceSats: 0, Payment: tagValue(ev, "payment"), Mint: tagValue(ev, "mint"), Token: tagValue(ev, "token"), ZapReceipt: tagValue(ev, "zap"), } if o.Coordinate == "" && o.AssetID == "" { return nil, fmt.Errorf("orders: order names no asset") } if o.AssetID != "" && !deed.IsAssetID(o.AssetID) { return nil, fmt.Errorf("orders: order asset id is invalid") } switch o.Tier { case deed.TierFan, deed.TierRetail: if o.Coordinate == "" { // A fan/retail order must name the coordinate it saw, so the seller // can check the price against what was offered. return nil, fmt.Errorf("orders: %s order has no coordinate", o.Tier) } case deed.TierSub: if o.Channel == "" { return nil, fmt.Errorf("orders: sub order has no channel") } default: return nil, fmt.Errorf("orders: unrecognized tier %q", o.Tier) } if price := tagValue(ev, "price"); price != "" { n, err := strconv.ParseInt(price, 10, 64) if err != nil || n < 0 { return nil, fmt.Errorf("orders: order price %q is invalid", price) } o.PriceSats = n } if period := tagValue(ev, "period"); period != "" { n, err := strconv.ParseInt(period, 10, 64) if err != nil || n < 0 { return nil, fmt.Errorf("orders: order period %q is invalid", period) } o.Period = n } if p := ev.Tags.GetFirst([]byte("p")); p != nil { raw, err := hex.DecodeString(string(p.ValueHex())) if err != nil || len(raw) != 32 { return nil, fmt.Errorf("orders: order seller tag is invalid") } o.Seller = raw } return o, nil } // AssetView is what the seller knows about the asset at validation time. type AssetView struct { AssetID string Coordinate string SourceEvent string Owner []byte PriceSats int64 Mints []string Retailers [][]byte ChannelMatch bool } // CheckOptions supplies the facts an order is checked against. type CheckOptions struct { // Asset is the resolved asset the order names. Asset *AssetView // Seller is this service's pubkey. When the order names a seller, it must // be this key. Seller []byte // Now overrides the clock. Now time.Time // MaxAge rejects a stale order; zero means 24 hours. MaxAge time.Duration // AcceptLightning enables the Lightning leg. The caller must have already // verified the zap receipt. AcceptLightning bool } // Check validates the order against the asset and this seller. // // The checks run in the order the specification requires: identity, asset, // price, payment method, mint, and presence of the proof. Settlement (the swap) // is the caller's next step and is not performed here. func (o *Order) Check(opts CheckOptions) error { if opts.Asset == nil { return fmt.Errorf("orders: asset is unknown") } if !deed.IsAssetID(opts.Asset.AssetID) { return fmt.Errorf("orders: resolved asset id is invalid") } if o.AssetID != "" && o.AssetID != opts.Asset.AssetID { return fmt.Errorf("orders: order names asset %s, resolved %s", o.AssetID, opts.Asset.AssetID) } if o.Coordinate != "" && opts.Asset.Coordinate != "" && o.Coordinate != opts.Asset.Coordinate { return fmt.Errorf("orders: order names coordinate %s, asset is at %s", o.Coordinate, opts.Asset.Coordinate) } if len(opts.Seller) == 32 && len(o.Seller) == 32 { if !equalBytes(o.Seller, opts.Seller) { return fmt.Errorf("orders: order is addressed to another seller") } } now := opts.Now if now.IsZero() { now = time.Now() } maxAge := opts.MaxAge if maxAge <= 0 { maxAge = 24 * time.Hour } if o.Event.CreatedAt > now.Add(5*time.Minute).Unix() { return fmt.Errorf("orders: order created_at is in the future") } if o.Event.CreatedAt < now.Add(-maxAge).Unix() { return fmt.Errorf("orders: order is stale") } if o.PriceSats < opts.Asset.PriceSats { return fmt.Errorf("orders: price %d is below the asset price %d", o.PriceSats, opts.Asset.PriceSats) } switch o.Payment { case PaymentCashu: if o.Token == "" { return fmt.Errorf("orders: cashu order has no token") } if o.Mint == "" { return fmt.Errorf("orders: cashu order has no mint") } if len(opts.Asset.Mints) > 0 && !containsFold(opts.Asset.Mints, o.Mint) { return fmt.Errorf("orders: mint %s is not accepted for this asset", o.Mint) } case PaymentLightning: if !opts.AcceptLightning { return fmt.Errorf("orders: lightning payment is not enabled") } if o.ZapReceipt == "" { return fmt.Errorf("orders: lightning order has no zap receipt") } case "": return fmt.Errorf("orders: order has no payment method") default: return fmt.Errorf("orders: unsupported payment method %q", o.Payment) } if o.Tier == deed.TierSub { if o.Period <= 0 { return fmt.Errorf("orders: sub order has no period") } if !opts.Asset.ChannelMatch { return fmt.Errorf("orders: asset is not in the subscribed channel") } } return nil } // RequiredGross returns the token value the buyer must supply: the net price // plus the mint input fee, which the buyer covers. func (o *Order) RequiredGross(inputFee uint64) uint64 { if o.PriceSats < 0 { return 0 } return uint64(o.PriceSats) + inputFee } // ExpiryFor returns the deed expiry for a subscription order. func (o *Order) ExpiryFor(now time.Time) int64 { if o.Tier != deed.TierSub || o.Period <= 0 { return 0 } return now.Add(time.Duration(o.Period) * time.Second).Unix() } 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()) } func containsFold(list []string, s string) bool { for _, v := range list { if strings.EqualFold(strings.TrimRight(v, "/"), strings.TrimRight(s, "/")) { return true } } return false } func equalBytes(a, b []byte) bool { if len(a) != len(b) { return false } var v byte for i := range a { v |= a[i] ^ b[i] } return v == 0 }