sales.go raw
1 // Package sales turns a validated purchase order into entitlement.
2 //
3 // The order of operations is the protocol's, not an implementation detail:
4 // unwrap and bind the buyer, resolve and check the asset and price, settle the
5 // payment, append the buyer to the ownership set, publish the asset identity
6 // record, and only then mint the signed deed. A failure at any step leaves the
7 // previous state intact, so a replay of the same order adds no second element
8 // and mints no second deed.
9 package sales
10
11 import (
12 "context"
13
14 "fmt"
15 "github.com/elnosh/gonuts/cashu"
16 "time"
17
18 "git.smesh.lol/orly/pkg/musiquay/access"
19 "git.smesh.lol/orly/pkg/musiquay/deed"
20 "git.smesh.lol/orly/pkg/musiquay/gcs"
21 "git.smesh.lol/orly/pkg/musiquay/orders"
22 "git.smesh.lol/orly/pkg/musiquay/subscriptions"
23 "git.smesh.lol/orly/pkg/nostr/encoders/event"
24 "git.smesh.lol/orly/pkg/nostr/encoders/hex"
25 "git.smesh.lol/orly/pkg/nostr/encoders/kind"
26 "git.smesh.lol/orly/pkg/nostr/encoders/tag"
27 "git.smesh.lol/orly/pkg/nostr/encoders/timestamp"
28 "git.smesh.lol/orly/pkg/nostr/interfaces/signer"
29 "git.smesh.lol/orly/pkg/nostr/protocol/nip59"
30 )
31
32 // AssetSource resolves an order's coordinate or asset id to what the seller
33 // knows about the asset. A database-backed implementation lives with the
34 // service wiring; tests supply a static one.
35 type AssetSource interface {
36 AssetByCoordinate(ctx context.Context, coordinate string) (*orders.AssetView, error)
37 AssetByID(ctx context.Context, assetID string) (*orders.AssetView, error)
38 }
39
40 // SetStore persists the raw pubkey list of an ownership set. The set blob
41 // itself lives on Blossom; this store is the seller's rebuild source.
42 type SetStore interface {
43 Load(ctx context.Context, d string) ([]string, error)
44 Save(ctx context.Context, d string, pubkeys []string) error
45 }
46
47 // PaymentSettler settles a token and reports the fee. claim.Minter implements
48 // it; tests supply a fake so the order path can be exercised without a mint.
49 type PaymentSettler interface {
50 Peek(tokenStr string) (cashu.Proofs, string, error)
51 InputFee(mintURL string, proofs cashu.Proofs) (uint64, error)
52 Receive(tokenStr, acceptedMint string, minSats uint64) (cashu.Proofs, error)
53 }
54
55 // BlobStore uploads bytes to Blossom and returns their SHA-256 hex.
56 type BlobStore interface {
57 Put(ctx context.Context, data []byte) (sha256Hex string, err error)
58 }
59
60 // Publisher publishes one event to the seller's relays.
61 type Publisher interface {
62 Publish(ctx context.Context, ev *event.E) error
63 }
64
65 // DeedArchive records the order -> deed link so a lost deed can be re-issued.
66 type DeedArchive interface {
67 Record(orderID, deedID string) error
68 }
69
70 // Config wires a sales service.
71 type Config struct {
72 // Sign is the owner (fan) or retailer (retail/sub) key.
73 Sign signer.I
74 // Minter settles Cashu payments.
75 Minter PaymentSettler
76 // Assets resolves the order's asset.
77 Assets AssetSource
78 // Sets persists ownership sets. Required.
79 Sets SetStore
80 // Blobs uploads filter blobs. Required.
81 Blobs BlobStore
82 // Relay publishes filter events and asset records.
83 Relay Publisher
84 // DeedPublisher publishes the deed wrap. When nil, Relay is used. Pointing
85 // it at a three-relay fan-out enforces the deed redundancy floor without
86 // making filter publication wait on three relays.
87 DeedPublisher Publisher
88 // Archive records order -> deed links. Optional.
89 Archive DeedArchive
90 // FilterServer is the server tag on filter events.
91 FilterServer string
92 // HashWidth is the element width; zero means 32.
93 HashWidth int
94 // DeedRelays is the minimum set of relays a deed wrap is published to. The
95 // Publisher is responsible for the fan-out; this field documents the floor.
96 DeedRelays []string
97 // EnsureRecord publishes a 3224 asset identity record when none is known.
98 EnsureRecord bool
99 // AcceptLightning enables the Lightning leg after the verifier runs.
100 AcceptLightning bool
101 // AllowSubscriptions enables channel subscription sales. V1-lite is
102 // ownership only; the default refuses a sub order rather than writing it
103 // into an ownership set.
104 AllowSubscriptions bool
105 // Subscriptions stores per-member expiries. Required when
106 // AllowSubscriptions is set.
107 Subscriptions *subscriptions.Manager
108 // VerifyLightning must verify the zap receipt through the LNURL server or a
109 // provider allowlist. A nil value refuses every Lightning order.
110 VerifyLightning func(ctx context.Context, o *orders.Order) error
111 // Now overrides the clock.
112 Now func() time.Time
113 }
114
115 // Service processes orders.
116 type Service struct {
117 cfg Config
118 }
119
120 // New creates a sales service.
121 func New(cfg Config) (*Service, error) {
122 if cfg.Sign == nil {
123 return nil, fmt.Errorf("sales: no signing key")
124 }
125 if cfg.Sets == nil {
126 return nil, fmt.Errorf("sales: no set store")
127 }
128 if cfg.Blobs == nil {
129 return nil, fmt.Errorf("sales: no blob store")
130 }
131 if cfg.Relay == nil {
132 return nil, fmt.Errorf("sales: no publisher")
133 }
134 if cfg.Assets == nil {
135 return nil, fmt.Errorf("sales: no asset source")
136 }
137 if cfg.Minter == nil && cfg.AcceptLightning {
138 return nil, fmt.Errorf("sales: cashu minter is required")
139 }
140 if cfg.AllowSubscriptions && cfg.Subscriptions == nil {
141 return nil, fmt.Errorf("sales: subscriptions are enabled without a store")
142 }
143 if cfg.HashWidth <= 0 {
144 cfg.HashWidth = 32
145 }
146 if cfg.Now == nil {
147 cfg.Now = time.Now
148 }
149 return &Service{cfg: cfg}, nil
150 }
151
152 // Result is what one successful sale produced.
153 type Result struct {
154 Order *orders.Order
155 Asset *orders.AssetView
156 Deed *deed.Deed
157 DeedEvent *event.E
158 DeedWrap *event.E
159 Filter *event.E
160 Record *event.E
161 FilterBlob string
162 PaymentRef string
163 }
164
165 // HandleOrder validates and fulfils one order.
166 //
167 // sealAuthor is the verified author of the NIP-59 seal that carried the order.
168 // It must equal the rumor author, otherwise a third party could order on
169 // someone else's behalf.
170 func (s *Service) HandleOrder(ctx context.Context, orderEv *event.E, sealAuthor []byte) (*Result, error) {
171 o, err := orders.ParseOrder(orderEv)
172 if err != nil {
173 return nil, err
174 }
175 if len(sealAuthor) != 32 || !bytesEqual(o.Buyer, sealAuthor) {
176 return nil, fmt.Errorf("sales: order author does not match the seal author")
177 }
178
179 var view *orders.AssetView
180 if o.AssetID != "" {
181 view, err = s.cfg.Assets.AssetByID(ctx, o.AssetID)
182 } else {
183 view, err = s.cfg.Assets.AssetByCoordinate(ctx, o.Coordinate)
184 }
185 if err != nil {
186 return nil, fmt.Errorf("sales: resolve asset: %w", err)
187 }
188 if o.Tier == deed.TierSub {
189 if !s.cfg.AllowSubscriptions {
190 return nil, fmt.Errorf("sales: subscriptions are not enabled on this service")
191 }
192 // The channel catalog is authoritative; the source sets the flag after
193 // looking the asset up inside the channel.
194 if !view.ChannelMatch {
195 return nil, fmt.Errorf("sales: asset is not in the channel catalog")
196 }
197 }
198 if !bytesEqual(view.Owner, s.cfg.Sign.Pub()) && !containsKey(view.Retailers, s.cfg.Sign.Pub()) {
199 return nil, fmt.Errorf("sales: this key may not sell the asset")
200 }
201
202 if err = o.Check(orders.CheckOptions{
203 Asset: view,
204 Seller: s.cfg.Sign.Pub(),
205 Now: s.cfg.Now(),
206 AcceptLightning: s.cfg.AcceptLightning && s.cfg.VerifyLightning != nil,
207 }); err != nil {
208 return nil, err
209 }
210
211 res := &Result{Order: o, Asset: view}
212
213 // Settle before granting. The swap is what proves the proofs are unspent;
214 // the mint, not this process, is the authority on replay.
215 switch o.Payment {
216 case orders.PaymentCashu:
217 if s.cfg.Minter == nil {
218 return nil, fmt.Errorf("sales: no cashu settler is configured")
219 }
220 proofs, mint, err := s.cfg.Minter.Peek(o.Token)
221 if err != nil {
222 return nil, err
223 }
224 fee, err := s.cfg.Minter.InputFee(mint, proofs)
225 if err != nil {
226 return nil, fmt.Errorf("sales: input fee: %w", err)
227 }
228 gross := o.RequiredGross(fee)
229 received, err := s.cfg.Minter.Receive(o.Token, o.Mint, gross)
230 if err != nil {
231 return nil, fmt.Errorf("sales: claim: %w", err)
232 }
233 res.PaymentRef = hex.Enc(proofsHash(received))
234 case orders.PaymentLightning:
235 if err = s.cfg.VerifyLightning(ctx, o); err != nil {
236 return nil, fmt.Errorf("sales: lightning: %w", err)
237 }
238 res.PaymentRef = o.ZapReceipt
239 }
240
241 // Append the buyer to the ownership set and publish the new filter.
242 filterEv, blobX, err := s.appendAndPublishSet(ctx, view, o)
243 if err != nil {
244 return nil, err
245 }
246 res.Filter = filterEv
247 res.FilterBlob = blobX
248
249 // Publish the asset identity record when asked and none exists yet.
250 if s.cfg.EnsureRecord && view.SourceEvent != "" {
251 rec, err := s.publishRecord(ctx, view)
252 if err != nil {
253 return nil, err
254 }
255 res.Record = rec
256 }
257
258 // Mint the deed only after the entitlement exists.
259 expires := o.ExpiryFor(s.cfg.Now())
260 deedAssetID, deedChannel := view.AssetID, ""
261 if o.Tier == deed.TierSub {
262 // A subscription names a channel, never an asset.
263 deedAssetID, deedChannel = "", o.Channel
264 }
265 deedEv, err := deed.Issue(s.cfg.Sign, deed.IssueOptions{
266 AssetID: deedAssetID,
267 Channel: deedChannel,
268 Tier: o.Tier,
269 Buyer: o.Buyer,
270 Order: hex.Enc(orderEv.ID),
271 Payment: res.PaymentRef,
272 PriceSats: o.PriceSats,
273 Expires: expires,
274 })
275 if err != nil {
276 return nil, fmt.Errorf("sales: issue deed: %w", err)
277 }
278 wrap, _, err := nip59.Wrap(s.cfg.Sign, o.Buyer, deedEv, nil)
279 if err != nil {
280 return nil, fmt.Errorf("sales: wrap deed: %w", err)
281 }
282 deedPub := s.cfg.DeedPublisher
283 if deedPub == nil {
284 deedPub = s.cfg.Relay
285 }
286 if err = deedPub.Publish(ctx, wrap); err != nil {
287 return nil, fmt.Errorf("sales: publish deed wrap: %w", err)
288 }
289 d, err := deed.ParseDeed(deedEv)
290 if err != nil {
291 return nil, err
292 }
293 res.Deed = d
294 res.DeedEvent = deedEv
295 res.DeedWrap = wrap
296 if s.cfg.Archive != nil {
297 if err = s.cfg.Archive.Record(hex.Enc(orderEv.ID), d.ID()); err != nil {
298 return nil, fmt.Errorf("sales: archive deed: %w", err)
299 }
300 }
301 return res, nil
302 }
303
304 // appendAndPublishSet appends the buyer and publishes the resulting 32217.
305 //
306 // Ownership sets are append-only: the load/add/save path never removes an
307 // element and never has an expiry. A repeated order for the same buyer produces
308 // a byte-identical set, so it adds nothing and the buyer downloads immediately.
309 func (s *Service) appendAndPublishSet(ctx context.Context, view *orders.AssetView, o *orders.Order) (*event.E, string, error) {
310 if o.Tier == deed.TierSub {
311 return s.appendAndPublishSubscription(ctx, view, o)
312 }
313 tier := "fan"
314 if o.Tier == deed.TierRetail {
315 tier = "retail"
316 }
317 d := tier + ":" + view.Coordinate
318
319 existing, err := s.cfg.Sets.Load(ctx, d)
320 if err != nil {
321 return nil, "", fmt.Errorf("sales: load set: %w", err)
322 }
323 seen := make(map[string]struct{}, len(existing)+1)
324 pubkeys := make([][]byte, 0, len(existing)+1)
325 for _, h := range existing {
326 raw, derr := hex.Dec(h)
327 if derr != nil || len(raw) != 32 {
328 continue
329 }
330 seen[string(raw)] = struct{}{}
331 pubkeys = append(pubkeys, raw)
332 }
333 if _, ok := seen[string(o.Buyer)]; !ok {
334 pubkeys = append(pubkeys, o.Buyer)
335 }
336
337 set, err := gcs.Build(view.Coordinate, pubkeys, s.cfg.HashWidth)
338 if err != nil {
339 return nil, "", fmt.Errorf("sales: build set: %w", err)
340 }
341 blob, err := set.Marshal()
342 if err != nil {
343 return nil, "", fmt.Errorf("sales: marshal set: %w", err)
344 }
345 x, err := s.cfg.Blobs.Put(ctx, blob)
346 if err != nil {
347 return nil, "", fmt.Errorf("sales: upload set: %w", err)
348 }
349
350 // Rebuild the pubkey list canonicalised through the set, so the stored list
351 // and the blob can never disagree.
352 stored := make([]string, 0, len(pubkeys))
353 for _, pk := range pubkeys {
354 stored = append(stored, hex.Enc(pk))
355 }
356
357 ev, err := access.BuildEvent(access.BuildOptions{
358 Owner: s.cfg.Sign.Pub(),
359 D: d,
360 X: x,
361 N: set.N,
362 HashWidth: s.cfg.HashWidth,
363 Server: s.cfg.FilterServer,
364 })
365 if err != nil {
366 return nil, "", err
367 }
368 ev.CreatedAt = timestamp.Now().I64()
369 if err = ev.Sign(s.cfg.Sign); err != nil {
370 return nil, "", fmt.Errorf("sales: sign filter: %w", err)
371 }
372 if err = s.cfg.Relay.Publish(ctx, ev); err != nil {
373 return nil, "", fmt.Errorf("sales: publish filter: %w", err)
374 }
375 if err = s.cfg.Sets.Save(ctx, d, stored); err != nil {
376 return nil, "", fmt.Errorf("sales: save set: %w", err)
377 }
378 return ev, x, nil
379 }
380
381 // publishRecord publishes the root 3224 asset identity record. The root must be
382 // signed by the source event's author, which is the seller in the single-owner
383 // deployment.
384 func (s *Service) publishRecord(ctx context.Context, view *orders.AssetView) (*event.E, error) {
385 ev := event.New()
386 ev.Kind = kind.AssetIdentity.ToU16()
387 ev.CreatedAt = timestamp.Now().I64()
388 ev.Tags = newTags(
389 []string{deed.TagD, view.AssetID},
390 []string{deed.TagSource, view.SourceEvent},
391 []string{deed.TagCoordinate, view.Coordinate},
392 []string{deed.TagOwner, hex.Enc(view.Owner)},
393 )
394 if err := ev.Sign(s.cfg.Sign); err != nil {
395 return nil, fmt.Errorf("sales: sign record: %w", err)
396 }
397 if err := s.cfg.Relay.Publish(ctx, ev); err != nil {
398 return nil, fmt.Errorf("sales: publish record: %w", err)
399 }
400 return ev, nil
401 }
402
403 func proofsHash(proofs interface{ Amount() uint64 }) []byte {
404 // A payment reference is not a token; hash the total and count so receipts
405 // can link a serve to a settlement without exposing proofs.
406 var b [16]byte
407 total := proofs.Amount()
408 for i := 0; i < 8; i++ {
409 b[i] = byte(total >> (8 * i))
410 }
411 return b[:]
412 }
413
414 func bytesEqual(a, b []byte) bool {
415 if len(a) != len(b) {
416 return false
417 }
418 var v byte
419 for i := range a {
420 v |= a[i] ^ b[i]
421 }
422 return v == 0
423 }
424
425 func containsKey(list [][]byte, k []byte) bool {
426 for _, v := range list {
427 if bytesEqual(v, k) {
428 return true
429 }
430 }
431 return false
432 }
433
434 // newTags builds a tag set from string tuples.
435 func newTags(items ...[]string) *tag.S {
436 s := tag.NewS()
437 for _, item := range items {
438 t := tag.New()
439 for _, v := range item {
440 t.T = append(t.T, []byte(v))
441 }
442 s.Append(t)
443 }
444 return s
445 }
446
447 // appendAndPublishSubscription adds or renews one subscriber and republishes
448 // the channel set with the lapsed members dropped.
449 func (s *Service) appendAndPublishSubscription(ctx context.Context, view *orders.AssetView, o *orders.Order) (*event.E, string, error) {
450 if s.cfg.Subscriptions == nil {
451 return nil, "", fmt.Errorf("sales: no subscription store")
452 }
453 retailer := hex.Enc(s.cfg.Sign.Pub())
454 expires := o.ExpiryFor(s.cfg.Now())
455 if err := s.cfg.Subscriptions.Add(ctx, retailer, o.Channel, o.Buyer, expires); err != nil {
456 return nil, "", fmt.Errorf("sales: add subscriber: %w", err)
457 }
458 live, err := s.cfg.Subscriptions.Rebuild(ctx, retailer, o.Channel)
459 if err != nil {
460 return nil, "", fmt.Errorf("sales: rebuild subscription: %w", err)
461 }
462 pubkeys := make([][]byte, 0, len(live))
463 for _, m := range live {
464 raw, derr := hex.Dec(m.Pubkey)
465 if derr != nil || len(raw) != 32 {
466 continue
467 }
468 pubkeys = append(pubkeys, raw)
469 }
470 d := "sub:" + retailer + ":" + o.Channel
471 set, err := gcs.Build(d, pubkeys, s.cfg.HashWidth)
472 if err != nil {
473 return nil, "", fmt.Errorf("sales: build subscription set: %w", err)
474 }
475 blob, err := set.Marshal()
476 if err != nil {
477 return nil, "", err
478 }
479 x, err := s.cfg.Blobs.Put(ctx, blob)
480 if err != nil {
481 return nil, "", fmt.Errorf("sales: upload subscription set: %w", err)
482 }
483 ev, err := access.BuildEvent(access.BuildOptions{
484 Owner: s.cfg.Sign.Pub(),
485 D: d,
486 X: x,
487 N: set.N,
488 HashWidth: s.cfg.HashWidth,
489 Server: s.cfg.FilterServer,
490 Channel: o.Channel,
491 Catalog: []string{view.Coordinate},
492 Expiration: expires,
493 })
494 if err != nil {
495 return nil, "", err
496 }
497 ev.CreatedAt = timestamp.Now().I64()
498 if err = ev.Sign(s.cfg.Sign); err != nil {
499 return nil, "", fmt.Errorf("sales: sign subscription filter: %w", err)
500 }
501 if err = s.cfg.Relay.Publish(ctx, ev); err != nil {
502 return nil, "", fmt.Errorf("sales: publish subscription filter: %w", err)
503 }
504 return ev, x, nil
505 }
506