receipts.go raw
1 // Package receipts implements musiquay delivery receipts and the accounting
2 // that derives from them.
3 //
4 // A receipt is a kind 32218 rumor carried in a NIP-59 gift wrap: one wrap to the
5 // buyer, one to the publisher. Receipts are rumors, not signed events, because
6 // the recipient verifies the host's seal signature and no third party needs to
7 // verify a receipt. Every serve produces one.
8 //
9 // The archive is the durable record. Aggregates (32219) are recomputed from it
10 // and are immutable; rollups (32220) reference the surviving aggregates by id.
11 package receipts
12
13 import (
14 "encoding/json"
15 "fmt"
16 "sort"
17 "strconv"
18 "strings"
19 "sync"
20 "time"
21
22 "git.smesh.lol/orly/pkg/musiquay/deed"
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 // Modes a receipt can record.
33 const (
34 ModeDownload = "download"
35 ModeStream = "stream"
36 )
37
38 // Receipt is the 32218 payload. Numeric values are strings on the wire, as the
39 // specification shows them, so a 64-bit byte count cannot lose precision in a
40 // JSON client that parses numbers as doubles.
41 type Receipt struct {
42 Kind int `json:"kind"`
43 Asset string `json:"asset"`
44 Coordinate string `json:"coordinate"`
45 Buyer string `json:"buyer"`
46 Blob string `json:"blob"`
47 Server string `json:"server"`
48 Mode string `json:"mode"`
49 Start string `json:"start"`
50 End string `json:"end"`
51 Bytes string `json:"bytes"`
52 AmountSats string `json:"amount_sats"`
53 Paid []string `json:"paid"`
54 // Period is archive-local; it is not part of the wire payload.
55 Period string `json:"-"`
56 }
57
58 // New builds a receipt for one serve.
59 func New(assetID, coordinate, buyer, blob, server, mode string, bytes, amountSats int64, paid []string) *Receipt {
60 now := time.Now().Unix()
61 return &Receipt{
62 Kind: kind.DeliveryReceipt.ToInt(),
63 Asset: assetID,
64 Coordinate: coordinate,
65 Buyer: buyer,
66 Blob: blob,
67 Server: server,
68 Mode: mode,
69 Start: strconv.FormatInt(now, 10),
70 End: strconv.FormatInt(now, 10),
71 Bytes: strconv.FormatInt(bytes, 10),
72 AmountSats: strconv.FormatInt(amountSats, 10),
73 Paid: paid,
74 }
75 }
76
77 // Validate checks the fields the accounting depends on.
78 func (r *Receipt) Validate() error {
79 if r == nil {
80 return fmt.Errorf("receipts: nil receipt")
81 }
82 if !deed.IsAssetID(r.Asset) {
83 return fmt.Errorf("receipts: invalid asset id %q", r.Asset)
84 }
85 if len(r.Buyer) != 64 {
86 return fmt.Errorf("receipts: invalid buyer")
87 }
88 if r.Blob == "" || len(r.Blob) != 64 {
89 return fmt.Errorf("receipts: invalid blob hash")
90 }
91 if r.Server == "" {
92 return fmt.Errorf("receipts: missing server")
93 }
94 if r.Mode != ModeDownload && r.Mode != ModeStream {
95 return fmt.Errorf("receipts: mode %q is not download or stream", r.Mode)
96 }
97 return nil
98 }
99
100 // Sats returns the settled amount.
101 func (r *Receipt) Sats() int64 {
102 n, _ := strconv.ParseInt(r.AmountSats, 10, 64)
103 return n
104 }
105
106 // BytesN returns the byte count.
107 func (r *Receipt) BytesN() int64 {
108 n, _ := strconv.ParseInt(r.Bytes, 10, 64)
109 return n
110 }
111
112 // Issued is the pair of wraps a serve produces.
113 type Issued struct {
114 // Rumor is the 32218 payload event (unsigned).
115 Rumor *event.E
116 // ToBuyer and ToPublisher are the two kind 1059 wraps.
117 ToBuyer *event.E
118 ToPublisher *event.E
119 // BuyerSeal and PublisherSeal are exposed for tests.
120 BuyerSeal *event.E
121 PublisherSeal *event.E
122 }
123
124 // Issue builds the receipt rumor and seals it to the buyer and the publisher.
125 //
126 // Both wraps are signed by the host's receipt key. The caller publishes each
127 // wrap to the recipient's relays; publishing is deliberately not done here so
128 // the gate can decide the serve before any network write.
129 func Issue(sign signer.I, r *Receipt, publisherPub []byte, cfg *nip59.Config) (*Issued, error) {
130 if err := r.Validate(); err != nil {
131 return nil, err
132 }
133 buyer, err := hex.Dec(r.Buyer)
134 if err != nil || len(buyer) != 32 {
135 return nil, fmt.Errorf("receipts: decode buyer: %v", err)
136 }
137 body, err := json.Marshal(r)
138 if err != nil {
139 return nil, fmt.Errorf("receipts: marshal receipt: %w", err)
140 }
141
142 rumor := event.New()
143 rumor.Kind = kind.DeliveryReceipt.ToU16()
144 rumor.CreatedAt = timestamp.Now().I64()
145 rumor.Tags = tag.NewS()
146 rumor.Tags.Append(tag.NewFromBytesSlice([]byte(deed.TagAsset), []byte(r.Asset)))
147 rumor.Tags.Append(tag.NewFromBytesSlice([]byte("p"), []byte(hex.Enc(buyer))))
148 rumor.Tags.Append(tag.NewFromBytesSlice([]byte("blob"), []byte(r.Blob)))
149 rumor.Tags.Append(tag.NewFromBytesSlice([]byte("mode"), []byte(r.Mode)))
150 rumor.Tags.Append(tag.NewFromBytesSlice([]byte("server"), []byte(r.Server)))
151 if r.Coordinate != "" {
152 rumor.Tags.Append(tag.NewFromBytesSlice([]byte("a"), []byte(r.Coordinate)))
153 }
154 pub := sign.Pub()
155 rumor.Pubkey = append([]byte(nil), pub...)
156 rumor.Content = body
157 rumor.ID = rumor.GetIDBytes()
158
159 out := &Issued{Rumor: rumor}
160 out.ToBuyer, out.BuyerSeal, err = nip59.Wrap(sign, buyer, rumor, cfg)
161 if err != nil {
162 return nil, fmt.Errorf("receipts: wrap to buyer: %w", err)
163 }
164 if len(publisherPub) == 32 {
165 out.ToPublisher, out.PublisherSeal, err = nip59.Wrap(sign, publisherPub, rumor, cfg)
166 if err != nil {
167 return nil, fmt.Errorf("receipts: wrap to publisher: %w", err)
168 }
169 }
170 return out, nil
171 }
172
173 // Period returns the archive bucket for a time: UTC day.
174 func Period(t time.Time) string { return t.UTC().Format("2006-01-02") }
175
176 // Store is the marker persistence the archive needs. database.Database
177 // satisfies it.
178 type Store interface {
179 SetMarker(key string, value []byte) error
180 GetMarker(key string) (value []byte, err error)
181 }
182
183 // Archive stores receipts durably, keyed by asset and period.
184 type Archive struct {
185 db Store
186 mu sync.Mutex
187 }
188
189 // NewArchive creates an archive on the relay database.
190 func NewArchive(db Store) *Archive { return &Archive{db: db} }
191
192 func bucketKey(assetID, period string) string {
193 return "musiquay:receipts:" + assetID + ":" + period
194 }
195 func indexKey(assetID string) string { return "musiquay:receipts:index:" + assetID }
196
197 // assetsKey indexes every asset the archive holds, so the publisher can
198 // enumerate its work without a database prefix scan.
199 const assetsKey = "musiquay:receipts:assets"
200
201 // Add appends a receipt to its (asset, period) bucket and to the asset index.
202 func (a *Archive) Add(r *Receipt) error {
203 if err := r.Validate(); err != nil {
204 return err
205 }
206 if r.Period == "" {
207 now := time.Now()
208 if n, err := strconv.ParseInt(r.End, 10, 64); err == nil && n > 0 {
209 now = time.Unix(n, 0)
210 }
211 r.Period = Period(now)
212 }
213 a.mu.Lock()
214 defer a.mu.Unlock()
215
216 bucket, err := a.load(bucketKey(r.Asset, r.Period))
217 if err != nil {
218 return err
219 }
220 bucket = append(bucket, *r)
221 if err = a.store(bucketKey(r.Asset, r.Period), bucket); err != nil {
222 return err
223 }
224
225 periods, err := a.periodsLocked(r.Asset)
226 if err != nil {
227 return err
228 }
229 for _, p := range periods {
230 if p == r.Period {
231 return nil
232 }
233 }
234 periods = append(periods, r.Period)
235 sort.Strings(periods)
236 if err = a.store(indexKey(r.Asset), periods); err != nil {
237 return err
238 }
239 assets, err := a.assetsLocked()
240 if err != nil {
241 return err
242 }
243 for _, asset := range assets {
244 if asset == r.Asset {
245 return nil
246 }
247 }
248 assets = append(assets, r.Asset)
249 sort.Strings(assets)
250 return a.store(assetsKey, assets)
251 }
252
253 // Assets returns every asset with archived receipts.
254 func (a *Archive) Assets() ([]string, error) {
255 a.mu.Lock()
256 defer a.mu.Unlock()
257 return a.assetsLocked()
258 }
259
260 func (a *Archive) assetsLocked() ([]string, error) {
261 data, err := a.db.GetMarker(assetsKey)
262 if err != nil || len(data) == 0 {
263 return nil, nil
264 }
265 var assets []string
266 if err = json.Unmarshal(data, &assets); err != nil {
267 return nil, fmt.Errorf("receipts: corrupt asset index: %w", err)
268 }
269 return assets, nil
270 }
271
272 // List returns the receipts for one asset and period.
273 func (a *Archive) List(assetID, period string) ([]Receipt, error) {
274 a.mu.Lock()
275 defer a.mu.Unlock()
276 return a.load(bucketKey(assetID, period))
277 }
278
279 // Periods returns the periods with archived receipts for an asset.
280 func (a *Archive) Periods(assetID string) ([]string, error) {
281 a.mu.Lock()
282 defer a.mu.Unlock()
283 return a.periodsLocked(assetID)
284 }
285
286 func (a *Archive) periodsLocked(assetID string) ([]string, error) {
287 data, err := a.db.GetMarker(indexKey(assetID))
288 if err != nil || len(data) == 0 {
289 return nil, nil
290 }
291 var periods []string
292 if err = json.Unmarshal(data, &periods); err != nil {
293 return nil, fmt.Errorf("receipts: corrupt period index: %w", err)
294 }
295 return periods, nil
296 }
297
298 func (a *Archive) load(key string) ([]Receipt, error) {
299 data, err := a.db.GetMarker(key)
300 if err != nil || len(data) == 0 {
301 return nil, nil
302 }
303 var rs []Receipt
304 if err = json.Unmarshal(data, &rs); err != nil {
305 return nil, fmt.Errorf("receipts: corrupt bucket %s: %w", key, err)
306 }
307 return rs, nil
308 }
309
310 func (a *Archive) store(key string, v any) error {
311 b, err := json.Marshal(v)
312 if err != nil {
313 return err
314 }
315 return a.db.SetMarker(key, b)
316 }
317
318 // Totals is the exact accounting for one asset, host, and period.
319 type Totals struct {
320 AssetID string `json:"asset"`
321 Host string `json:"host"`
322 Period string `json:"period"`
323 Plays int64 `json:"plays"`
324 Downloads int64 `json:"downloads"`
325 Bytes int64 `json:"bytes"`
326 Sats int64 `json:"sats"`
327 Listeners int64 `json:"listeners"`
328 }
329
330 // Compute recomputes totals from receipts. It is deterministic: the same input
331 // always produces the same Totals.
332 func Compute(rs []Receipt, assetID, host, period string) Totals {
333 t := Totals{AssetID: assetID, Host: host, Period: period}
334 buyers := make(map[string]struct{})
335 for i := range rs {
336 r := &rs[i]
337 if host != "" && r.Server != host {
338 continue
339 }
340 if r.Mode == ModeStream {
341 t.Plays++
342 } else {
343 t.Downloads++
344 }
345 t.Bytes += r.BytesN()
346 t.Sats += r.Sats()
347 if r.Buyer != "" {
348 buyers[r.Buyer] = struct{}{}
349 }
350 }
351 t.Listeners = int64(len(buyers))
352 return t
353 }
354
355 // PublishAggregate builds and signs an immutable kind 32219 aggregate.
356 func PublishAggregate(sign signer.I, t Totals) (*event.E, error) {
357 if !deed.IsAssetID(t.AssetID) {
358 return nil, fmt.Errorf("receipts: invalid asset id")
359 }
360 if t.Period == "" {
361 return nil, fmt.Errorf("receipts: aggregate needs a period")
362 }
363 body, err := json.Marshal(t)
364 if err != nil {
365 return nil, err
366 }
367 ev := event.New()
368 ev.Kind = kind.HostAggregate.ToU16()
369 ev.CreatedAt = timestamp.Now().I64()
370 ev.Tags = tag.NewS()
371 ev.Tags.Append(tag.NewFromBytesSlice([]byte(deed.TagAsset), []byte(t.AssetID)))
372 ev.Tags.Append(tag.NewFromBytesSlice([]byte("period"), []byte(t.Period)))
373 if t.Host != "" {
374 ev.Tags.Append(tag.NewFromBytesSlice([]byte("server"), []byte(t.Host)))
375 }
376 ev.Tags.Append(tag.NewFromBytesSlice([]byte("plays"), []byte(strconv.FormatInt(t.Plays, 10))))
377 ev.Tags.Append(tag.NewFromBytesSlice([]byte("downloads"), []byte(strconv.FormatInt(t.Downloads, 10))))
378 ev.Tags.Append(tag.NewFromBytesSlice([]byte("bytes"), []byte(strconv.FormatInt(t.Bytes, 10))))
379 ev.Tags.Append(tag.NewFromBytesSlice([]byte("sats"), []byte(strconv.FormatInt(t.Sats, 10))))
380 ev.Tags.Append(tag.NewFromBytesSlice([]byte("listeners"), []byte(strconv.FormatInt(t.Listeners, 10))))
381 ev.Content = body
382 if err = ev.Sign(sign); err != nil {
383 return nil, fmt.Errorf("receipts: sign aggregate: %w", err)
384 }
385 return ev, nil
386 }
387
388 // Rollup sums surviving host aggregates and signs a kind 32220 that references
389 // each one by e tag. A deleted aggregate therefore drops out of both the sum and
390 // the reference list.
391 func Rollup(sign signer.I, assetID, period, publisher string, ownReceipts int64, aggregates []*event.E) (*event.E, error) {
392 if !deed.IsAssetID(assetID) {
393 return nil, fmt.Errorf("receipts: invalid asset id")
394 }
395 var t Totals
396 t.AssetID = assetID
397 t.Period = period
398 hosts := make([]string, 0, len(aggregates))
399 for _, ev := range aggregates {
400 if ev == nil || ev.Kind != kind.HostAggregate.ToU16() {
401 continue
402 }
403 if tagVal(ev, deed.TagAsset) != assetID || tagVal(ev, "period") != period {
404 continue
405 }
406 t.Plays += parseInt(tagVal(ev, "plays"))
407 t.Downloads += parseInt(tagVal(ev, "downloads"))
408 t.Bytes += parseInt(tagVal(ev, "bytes"))
409 t.Sats += parseInt(tagVal(ev, "sats"))
410 t.Listeners += parseInt(tagVal(ev, "listeners"))
411 if h := tagVal(ev, "server"); h != "" {
412 hosts = append(hosts, h)
413 }
414 }
415 sort.Strings(hosts)
416
417 body, err := json.Marshal(map[string]any{
418 "asset": assetID,
419 "period": period,
420 "publisher": publisher,
421 "hosts": hosts,
422 "plays": t.Plays,
423 "downloads": t.Downloads,
424 "bytes": t.Bytes,
425 "sats": t.Sats,
426 "listeners": t.Listeners,
427 "receipts": ownReceipts,
428 })
429 if err != nil {
430 return nil, err
431 }
432 ev := event.New()
433 ev.Kind = kind.PublisherRollup.ToU16()
434 ev.CreatedAt = timestamp.Now().I64()
435 ev.Tags = tag.NewS()
436 ev.Tags.Append(tag.NewFromBytesSlice([]byte(deed.TagAsset), []byte(assetID)))
437 ev.Tags.Append(tag.NewFromBytesSlice([]byte("period"), []byte(period)))
438 ev.Tags.Append(tag.NewFromBytesSlice([]byte("receipts"), []byte(strconv.FormatInt(ownReceipts, 10))))
439 for _, agg := range aggregates {
440 if agg == nil {
441 continue
442 }
443 ev.Tags.Append(tag.NewFromBytesSlice([]byte("e"), agg.ID))
444 }
445 ev.Content = body
446 if err = ev.Sign(sign); err != nil {
447 return nil, fmt.Errorf("receipts: sign rollup: %w", err)
448 }
449 return ev, nil
450 }
451
452 func tagVal(ev *event.E, name string) string {
453 if ev == nil || ev.Tags == nil {
454 return ""
455 }
456 t := ev.Tags.GetFirst([]byte(name))
457 if t == nil {
458 return ""
459 }
460 return string(t.Value())
461 }
462
463 func parseInt(s string) int64 {
464 n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
465 return n
466 }
467