// Package sales turns a validated purchase order into entitlement. // // The order of operations is the protocol's, not an implementation detail: // unwrap and bind the buyer, resolve and check the asset and price, settle the // payment, append the buyer to the ownership set, publish the asset identity // record, and only then mint the signed deed. A failure at any step leaves the // previous state intact, so a replay of the same order adds no second element // and mints no second deed. package sales import ( "context" "fmt" "github.com/elnosh/gonuts/cashu" "time" "git.smesh.lol/orly/pkg/musiquay/access" "git.smesh.lol/orly/pkg/musiquay/deed" "git.smesh.lol/orly/pkg/musiquay/gcs" "git.smesh.lol/orly/pkg/musiquay/orders" "git.smesh.lol/orly/pkg/musiquay/subscriptions" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/hex" "git.smesh.lol/orly/pkg/nostr/encoders/kind" "git.smesh.lol/orly/pkg/nostr/encoders/tag" "git.smesh.lol/orly/pkg/nostr/encoders/timestamp" "git.smesh.lol/orly/pkg/nostr/interfaces/signer" "git.smesh.lol/orly/pkg/nostr/protocol/nip59" ) // AssetSource resolves an order's coordinate or asset id to what the seller // knows about the asset. A database-backed implementation lives with the // service wiring; tests supply a static one. type AssetSource interface { AssetByCoordinate(ctx context.Context, coordinate string) (*orders.AssetView, error) AssetByID(ctx context.Context, assetID string) (*orders.AssetView, error) } // SetStore persists the raw pubkey list of an ownership set. The set blob // itself lives on Blossom; this store is the seller's rebuild source. type SetStore interface { Load(ctx context.Context, d string) ([]string, error) Save(ctx context.Context, d string, pubkeys []string) error } // PaymentSettler settles a token and reports the fee. claim.Minter implements // it; tests supply a fake so the order path can be exercised without a mint. type PaymentSettler interface { Peek(tokenStr string) (cashu.Proofs, string, error) InputFee(mintURL string, proofs cashu.Proofs) (uint64, error) Receive(tokenStr, acceptedMint string, minSats uint64) (cashu.Proofs, error) } // BlobStore uploads bytes to Blossom and returns their SHA-256 hex. type BlobStore interface { Put(ctx context.Context, data []byte) (sha256Hex string, err error) } // Publisher publishes one event to the seller's relays. type Publisher interface { Publish(ctx context.Context, ev *event.E) error } // DeedArchive records the order -> deed link so a lost deed can be re-issued. type DeedArchive interface { Record(orderID, deedID string) error } // Config wires a sales service. type Config struct { // Sign is the owner (fan) or retailer (retail/sub) key. Sign signer.I // Minter settles Cashu payments. Minter PaymentSettler // Assets resolves the order's asset. Assets AssetSource // Sets persists ownership sets. Required. Sets SetStore // Blobs uploads filter blobs. Required. Blobs BlobStore // Relay publishes filter events and asset records. Relay Publisher // DeedPublisher publishes the deed wrap. When nil, Relay is used. Pointing // it at a three-relay fan-out enforces the deed redundancy floor without // making filter publication wait on three relays. DeedPublisher Publisher // Archive records order -> deed links. Optional. Archive DeedArchive // FilterServer is the server tag on filter events. FilterServer string // HashWidth is the element width; zero means 32. HashWidth int // DeedRelays is the minimum set of relays a deed wrap is published to. The // Publisher is responsible for the fan-out; this field documents the floor. DeedRelays []string // EnsureRecord publishes a 3224 asset identity record when none is known. EnsureRecord bool // AcceptLightning enables the Lightning leg after the verifier runs. AcceptLightning bool // AllowSubscriptions enables channel subscription sales. V1-lite is // ownership only; the default refuses a sub order rather than writing it // into an ownership set. AllowSubscriptions bool // Subscriptions stores per-member expiries. Required when // AllowSubscriptions is set. Subscriptions *subscriptions.Manager // VerifyLightning must verify the zap receipt through the LNURL server or a // provider allowlist. A nil value refuses every Lightning order. VerifyLightning func(ctx context.Context, o *orders.Order) error // Now overrides the clock. Now func() time.Time } // Service processes orders. type Service struct { cfg Config } // New creates a sales service. func New(cfg Config) (*Service, error) { if cfg.Sign == nil { return nil, fmt.Errorf("sales: no signing key") } if cfg.Sets == nil { return nil, fmt.Errorf("sales: no set store") } if cfg.Blobs == nil { return nil, fmt.Errorf("sales: no blob store") } if cfg.Relay == nil { return nil, fmt.Errorf("sales: no publisher") } if cfg.Assets == nil { return nil, fmt.Errorf("sales: no asset source") } if cfg.Minter == nil && cfg.AcceptLightning { return nil, fmt.Errorf("sales: cashu minter is required") } if cfg.AllowSubscriptions && cfg.Subscriptions == nil { return nil, fmt.Errorf("sales: subscriptions are enabled without a store") } if cfg.HashWidth <= 0 { cfg.HashWidth = 32 } if cfg.Now == nil { cfg.Now = time.Now } return &Service{cfg: cfg}, nil } // Result is what one successful sale produced. type Result struct { Order *orders.Order Asset *orders.AssetView Deed *deed.Deed DeedEvent *event.E DeedWrap *event.E Filter *event.E Record *event.E FilterBlob string PaymentRef string } // HandleOrder validates and fulfils one order. // // sealAuthor is the verified author of the NIP-59 seal that carried the order. // It must equal the rumor author, otherwise a third party could order on // someone else's behalf. func (s *Service) HandleOrder(ctx context.Context, orderEv *event.E, sealAuthor []byte) (*Result, error) { o, err := orders.ParseOrder(orderEv) if err != nil { return nil, err } if len(sealAuthor) != 32 || !bytesEqual(o.Buyer, sealAuthor) { return nil, fmt.Errorf("sales: order author does not match the seal author") } var view *orders.AssetView if o.AssetID != "" { view, err = s.cfg.Assets.AssetByID(ctx, o.AssetID) } else { view, err = s.cfg.Assets.AssetByCoordinate(ctx, o.Coordinate) } if err != nil { return nil, fmt.Errorf("sales: resolve asset: %w", err) } if o.Tier == deed.TierSub { if !s.cfg.AllowSubscriptions { return nil, fmt.Errorf("sales: subscriptions are not enabled on this service") } // The channel catalog is authoritative; the source sets the flag after // looking the asset up inside the channel. if !view.ChannelMatch { return nil, fmt.Errorf("sales: asset is not in the channel catalog") } } if !bytesEqual(view.Owner, s.cfg.Sign.Pub()) && !containsKey(view.Retailers, s.cfg.Sign.Pub()) { return nil, fmt.Errorf("sales: this key may not sell the asset") } if err = o.Check(orders.CheckOptions{ Asset: view, Seller: s.cfg.Sign.Pub(), Now: s.cfg.Now(), AcceptLightning: s.cfg.AcceptLightning && s.cfg.VerifyLightning != nil, }); err != nil { return nil, err } res := &Result{Order: o, Asset: view} // Settle before granting. The swap is what proves the proofs are unspent; // the mint, not this process, is the authority on replay. switch o.Payment { case orders.PaymentCashu: if s.cfg.Minter == nil { return nil, fmt.Errorf("sales: no cashu settler is configured") } proofs, mint, err := s.cfg.Minter.Peek(o.Token) if err != nil { return nil, err } fee, err := s.cfg.Minter.InputFee(mint, proofs) if err != nil { return nil, fmt.Errorf("sales: input fee: %w", err) } gross := o.RequiredGross(fee) received, err := s.cfg.Minter.Receive(o.Token, o.Mint, gross) if err != nil { return nil, fmt.Errorf("sales: claim: %w", err) } res.PaymentRef = hex.Enc(proofsHash(received)) case orders.PaymentLightning: if err = s.cfg.VerifyLightning(ctx, o); err != nil { return nil, fmt.Errorf("sales: lightning: %w", err) } res.PaymentRef = o.ZapReceipt } // Append the buyer to the ownership set and publish the new filter. filterEv, blobX, err := s.appendAndPublishSet(ctx, view, o) if err != nil { return nil, err } res.Filter = filterEv res.FilterBlob = blobX // Publish the asset identity record when asked and none exists yet. if s.cfg.EnsureRecord && view.SourceEvent != "" { rec, err := s.publishRecord(ctx, view) if err != nil { return nil, err } res.Record = rec } // Mint the deed only after the entitlement exists. expires := o.ExpiryFor(s.cfg.Now()) deedAssetID, deedChannel := view.AssetID, "" if o.Tier == deed.TierSub { // A subscription names a channel, never an asset. deedAssetID, deedChannel = "", o.Channel } deedEv, err := deed.Issue(s.cfg.Sign, deed.IssueOptions{ AssetID: deedAssetID, Channel: deedChannel, Tier: o.Tier, Buyer: o.Buyer, Order: hex.Enc(orderEv.ID), Payment: res.PaymentRef, PriceSats: o.PriceSats, Expires: expires, }) if err != nil { return nil, fmt.Errorf("sales: issue deed: %w", err) } wrap, _, err := nip59.Wrap(s.cfg.Sign, o.Buyer, deedEv, nil) if err != nil { return nil, fmt.Errorf("sales: wrap deed: %w", err) } deedPub := s.cfg.DeedPublisher if deedPub == nil { deedPub = s.cfg.Relay } if err = deedPub.Publish(ctx, wrap); err != nil { return nil, fmt.Errorf("sales: publish deed wrap: %w", err) } d, err := deed.ParseDeed(deedEv) if err != nil { return nil, err } res.Deed = d res.DeedEvent = deedEv res.DeedWrap = wrap if s.cfg.Archive != nil { if err = s.cfg.Archive.Record(hex.Enc(orderEv.ID), d.ID()); err != nil { return nil, fmt.Errorf("sales: archive deed: %w", err) } } return res, nil } // appendAndPublishSet appends the buyer and publishes the resulting 32217. // // Ownership sets are append-only: the load/add/save path never removes an // element and never has an expiry. A repeated order for the same buyer produces // a byte-identical set, so it adds nothing and the buyer downloads immediately. func (s *Service) appendAndPublishSet(ctx context.Context, view *orders.AssetView, o *orders.Order) (*event.E, string, error) { if o.Tier == deed.TierSub { return s.appendAndPublishSubscription(ctx, view, o) } tier := "fan" if o.Tier == deed.TierRetail { tier = "retail" } d := tier + ":" + view.Coordinate existing, err := s.cfg.Sets.Load(ctx, d) if err != nil { return nil, "", fmt.Errorf("sales: load set: %w", err) } seen := make(map[string]struct{}, len(existing)+1) pubkeys := make([][]byte, 0, len(existing)+1) for _, h := range existing { raw, derr := hex.Dec(h) if derr != nil || len(raw) != 32 { continue } seen[string(raw)] = struct{}{} pubkeys = append(pubkeys, raw) } if _, ok := seen[string(o.Buyer)]; !ok { pubkeys = append(pubkeys, o.Buyer) } set, err := gcs.Build(view.Coordinate, pubkeys, s.cfg.HashWidth) if err != nil { return nil, "", fmt.Errorf("sales: build set: %w", err) } blob, err := set.Marshal() if err != nil { return nil, "", fmt.Errorf("sales: marshal set: %w", err) } x, err := s.cfg.Blobs.Put(ctx, blob) if err != nil { return nil, "", fmt.Errorf("sales: upload set: %w", err) } // Rebuild the pubkey list canonicalised through the set, so the stored list // and the blob can never disagree. stored := make([]string, 0, len(pubkeys)) for _, pk := range pubkeys { stored = append(stored, hex.Enc(pk)) } ev, err := access.BuildEvent(access.BuildOptions{ Owner: s.cfg.Sign.Pub(), D: d, X: x, N: set.N, HashWidth: s.cfg.HashWidth, Server: s.cfg.FilterServer, }) if err != nil { return nil, "", err } ev.CreatedAt = timestamp.Now().I64() if err = ev.Sign(s.cfg.Sign); err != nil { return nil, "", fmt.Errorf("sales: sign filter: %w", err) } if err = s.cfg.Relay.Publish(ctx, ev); err != nil { return nil, "", fmt.Errorf("sales: publish filter: %w", err) } if err = s.cfg.Sets.Save(ctx, d, stored); err != nil { return nil, "", fmt.Errorf("sales: save set: %w", err) } return ev, x, nil } // publishRecord publishes the root 3224 asset identity record. The root must be // signed by the source event's author, which is the seller in the single-owner // deployment. func (s *Service) publishRecord(ctx context.Context, view *orders.AssetView) (*event.E, error) { ev := event.New() ev.Kind = kind.AssetIdentity.ToU16() ev.CreatedAt = timestamp.Now().I64() ev.Tags = newTags( []string{deed.TagD, view.AssetID}, []string{deed.TagSource, view.SourceEvent}, []string{deed.TagCoordinate, view.Coordinate}, []string{deed.TagOwner, hex.Enc(view.Owner)}, ) if err := ev.Sign(s.cfg.Sign); err != nil { return nil, fmt.Errorf("sales: sign record: %w", err) } if err := s.cfg.Relay.Publish(ctx, ev); err != nil { return nil, fmt.Errorf("sales: publish record: %w", err) } return ev, nil } func proofsHash(proofs interface{ Amount() uint64 }) []byte { // A payment reference is not a token; hash the total and count so receipts // can link a serve to a settlement without exposing proofs. var b [16]byte total := proofs.Amount() for i := 0; i < 8; i++ { b[i] = byte(total >> (8 * i)) } return b[:] } func bytesEqual(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 } func containsKey(list [][]byte, k []byte) bool { for _, v := range list { if bytesEqual(v, k) { return true } } return false } // newTags builds a tag set from string tuples. func newTags(items ...[]string) *tag.S { s := tag.NewS() for _, item := range items { t := tag.New() for _, v := range item { t.T = append(t.T, []byte(v)) } s.Append(t) } return s } // appendAndPublishSubscription adds or renews one subscriber and republishes // the channel set with the lapsed members dropped. func (s *Service) appendAndPublishSubscription(ctx context.Context, view *orders.AssetView, o *orders.Order) (*event.E, string, error) { if s.cfg.Subscriptions == nil { return nil, "", fmt.Errorf("sales: no subscription store") } retailer := hex.Enc(s.cfg.Sign.Pub()) expires := o.ExpiryFor(s.cfg.Now()) if err := s.cfg.Subscriptions.Add(ctx, retailer, o.Channel, o.Buyer, expires); err != nil { return nil, "", fmt.Errorf("sales: add subscriber: %w", err) } live, err := s.cfg.Subscriptions.Rebuild(ctx, retailer, o.Channel) if err != nil { return nil, "", fmt.Errorf("sales: rebuild subscription: %w", err) } pubkeys := make([][]byte, 0, len(live)) for _, m := range live { raw, derr := hex.Dec(m.Pubkey) if derr != nil || len(raw) != 32 { continue } pubkeys = append(pubkeys, raw) } d := "sub:" + retailer + ":" + o.Channel set, err := gcs.Build(d, pubkeys, s.cfg.HashWidth) if err != nil { return nil, "", fmt.Errorf("sales: build subscription set: %w", err) } blob, err := set.Marshal() if err != nil { return nil, "", err } x, err := s.cfg.Blobs.Put(ctx, blob) if err != nil { return nil, "", fmt.Errorf("sales: upload subscription set: %w", err) } ev, err := access.BuildEvent(access.BuildOptions{ Owner: s.cfg.Sign.Pub(), D: d, X: x, N: set.N, HashWidth: s.cfg.HashWidth, Server: s.cfg.FilterServer, Channel: o.Channel, Catalog: []string{view.Coordinate}, Expiration: expires, }) if err != nil { return nil, "", err } ev.CreatedAt = timestamp.Now().I64() if err = ev.Sign(s.cfg.Sign); err != nil { return nil, "", fmt.Errorf("sales: sign subscription filter: %w", err) } if err = s.cfg.Relay.Publish(ctx, ev); err != nil { return nil, "", fmt.Errorf("sales: publish subscription filter: %w", err) } return ev, x, nil }