// Package receipts implements musiquay delivery receipts and the accounting // that derives from them. // // A receipt is a kind 32218 rumor carried in a NIP-59 gift wrap: one wrap to the // buyer, one to the publisher. Receipts are rumors, not signed events, because // the recipient verifies the host's seal signature and no third party needs to // verify a receipt. Every serve produces one. // // The archive is the durable record. Aggregates (32219) are recomputed from it // and are immutable; rollups (32220) reference the surviving aggregates by id. package receipts import ( "encoding/json" "fmt" "sort" "strconv" "strings" "sync" "time" "git.smesh.lol/orly/pkg/musiquay/deed" "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" ) // Modes a receipt can record. const ( ModeDownload = "download" ModeStream = "stream" ) // Receipt is the 32218 payload. Numeric values are strings on the wire, as the // specification shows them, so a 64-bit byte count cannot lose precision in a // JSON client that parses numbers as doubles. type Receipt struct { Kind int `json:"kind"` Asset string `json:"asset"` Coordinate string `json:"coordinate"` Buyer string `json:"buyer"` Blob string `json:"blob"` Server string `json:"server"` Mode string `json:"mode"` Start string `json:"start"` End string `json:"end"` Bytes string `json:"bytes"` AmountSats string `json:"amount_sats"` Paid []string `json:"paid"` // Period is archive-local; it is not part of the wire payload. Period string `json:"-"` } // New builds a receipt for one serve. func New(assetID, coordinate, buyer, blob, server, mode string, bytes, amountSats int64, paid []string) *Receipt { now := time.Now().Unix() return &Receipt{ Kind: kind.DeliveryReceipt.ToInt(), Asset: assetID, Coordinate: coordinate, Buyer: buyer, Blob: blob, Server: server, Mode: mode, Start: strconv.FormatInt(now, 10), End: strconv.FormatInt(now, 10), Bytes: strconv.FormatInt(bytes, 10), AmountSats: strconv.FormatInt(amountSats, 10), Paid: paid, } } // Validate checks the fields the accounting depends on. func (r *Receipt) Validate() error { if r == nil { return fmt.Errorf("receipts: nil receipt") } if !deed.IsAssetID(r.Asset) { return fmt.Errorf("receipts: invalid asset id %q", r.Asset) } if len(r.Buyer) != 64 { return fmt.Errorf("receipts: invalid buyer") } if r.Blob == "" || len(r.Blob) != 64 { return fmt.Errorf("receipts: invalid blob hash") } if r.Server == "" { return fmt.Errorf("receipts: missing server") } if r.Mode != ModeDownload && r.Mode != ModeStream { return fmt.Errorf("receipts: mode %q is not download or stream", r.Mode) } return nil } // Sats returns the settled amount. func (r *Receipt) Sats() int64 { n, _ := strconv.ParseInt(r.AmountSats, 10, 64) return n } // BytesN returns the byte count. func (r *Receipt) BytesN() int64 { n, _ := strconv.ParseInt(r.Bytes, 10, 64) return n } // Issued is the pair of wraps a serve produces. type Issued struct { // Rumor is the 32218 payload event (unsigned). Rumor *event.E // ToBuyer and ToPublisher are the two kind 1059 wraps. ToBuyer *event.E ToPublisher *event.E // BuyerSeal and PublisherSeal are exposed for tests. BuyerSeal *event.E PublisherSeal *event.E } // Issue builds the receipt rumor and seals it to the buyer and the publisher. // // Both wraps are signed by the host's receipt key. The caller publishes each // wrap to the recipient's relays; publishing is deliberately not done here so // the gate can decide the serve before any network write. func Issue(sign signer.I, r *Receipt, publisherPub []byte, cfg *nip59.Config) (*Issued, error) { if err := r.Validate(); err != nil { return nil, err } buyer, err := hex.Dec(r.Buyer) if err != nil || len(buyer) != 32 { return nil, fmt.Errorf("receipts: decode buyer: %v", err) } body, err := json.Marshal(r) if err != nil { return nil, fmt.Errorf("receipts: marshal receipt: %w", err) } rumor := event.New() rumor.Kind = kind.DeliveryReceipt.ToU16() rumor.CreatedAt = timestamp.Now().I64() rumor.Tags = tag.NewS() rumor.Tags.Append(tag.NewFromBytesSlice([]byte(deed.TagAsset), []byte(r.Asset))) rumor.Tags.Append(tag.NewFromBytesSlice([]byte("p"), []byte(hex.Enc(buyer)))) rumor.Tags.Append(tag.NewFromBytesSlice([]byte("blob"), []byte(r.Blob))) rumor.Tags.Append(tag.NewFromBytesSlice([]byte("mode"), []byte(r.Mode))) rumor.Tags.Append(tag.NewFromBytesSlice([]byte("server"), []byte(r.Server))) if r.Coordinate != "" { rumor.Tags.Append(tag.NewFromBytesSlice([]byte("a"), []byte(r.Coordinate))) } pub := sign.Pub() rumor.Pubkey = append([]byte(nil), pub...) rumor.Content = body rumor.ID = rumor.GetIDBytes() out := &Issued{Rumor: rumor} out.ToBuyer, out.BuyerSeal, err = nip59.Wrap(sign, buyer, rumor, cfg) if err != nil { return nil, fmt.Errorf("receipts: wrap to buyer: %w", err) } if len(publisherPub) == 32 { out.ToPublisher, out.PublisherSeal, err = nip59.Wrap(sign, publisherPub, rumor, cfg) if err != nil { return nil, fmt.Errorf("receipts: wrap to publisher: %w", err) } } return out, nil } // Period returns the archive bucket for a time: UTC day. func Period(t time.Time) string { return t.UTC().Format("2006-01-02") } // Store is the marker persistence the archive needs. database.Database // satisfies it. type Store interface { SetMarker(key string, value []byte) error GetMarker(key string) (value []byte, err error) } // Archive stores receipts durably, keyed by asset and period. type Archive struct { db Store mu sync.Mutex } // NewArchive creates an archive on the relay database. func NewArchive(db Store) *Archive { return &Archive{db: db} } func bucketKey(assetID, period string) string { return "musiquay:receipts:" + assetID + ":" + period } func indexKey(assetID string) string { return "musiquay:receipts:index:" + assetID } // assetsKey indexes every asset the archive holds, so the publisher can // enumerate its work without a database prefix scan. const assetsKey = "musiquay:receipts:assets" // Add appends a receipt to its (asset, period) bucket and to the asset index. func (a *Archive) Add(r *Receipt) error { if err := r.Validate(); err != nil { return err } if r.Period == "" { now := time.Now() if n, err := strconv.ParseInt(r.End, 10, 64); err == nil && n > 0 { now = time.Unix(n, 0) } r.Period = Period(now) } a.mu.Lock() defer a.mu.Unlock() bucket, err := a.load(bucketKey(r.Asset, r.Period)) if err != nil { return err } bucket = append(bucket, *r) if err = a.store(bucketKey(r.Asset, r.Period), bucket); err != nil { return err } periods, err := a.periodsLocked(r.Asset) if err != nil { return err } for _, p := range periods { if p == r.Period { return nil } } periods = append(periods, r.Period) sort.Strings(periods) if err = a.store(indexKey(r.Asset), periods); err != nil { return err } assets, err := a.assetsLocked() if err != nil { return err } for _, asset := range assets { if asset == r.Asset { return nil } } assets = append(assets, r.Asset) sort.Strings(assets) return a.store(assetsKey, assets) } // Assets returns every asset with archived receipts. func (a *Archive) Assets() ([]string, error) { a.mu.Lock() defer a.mu.Unlock() return a.assetsLocked() } func (a *Archive) assetsLocked() ([]string, error) { data, err := a.db.GetMarker(assetsKey) if err != nil || len(data) == 0 { return nil, nil } var assets []string if err = json.Unmarshal(data, &assets); err != nil { return nil, fmt.Errorf("receipts: corrupt asset index: %w", err) } return assets, nil } // List returns the receipts for one asset and period. func (a *Archive) List(assetID, period string) ([]Receipt, error) { a.mu.Lock() defer a.mu.Unlock() return a.load(bucketKey(assetID, period)) } // Periods returns the periods with archived receipts for an asset. func (a *Archive) Periods(assetID string) ([]string, error) { a.mu.Lock() defer a.mu.Unlock() return a.periodsLocked(assetID) } func (a *Archive) periodsLocked(assetID string) ([]string, error) { data, err := a.db.GetMarker(indexKey(assetID)) if err != nil || len(data) == 0 { return nil, nil } var periods []string if err = json.Unmarshal(data, &periods); err != nil { return nil, fmt.Errorf("receipts: corrupt period index: %w", err) } return periods, nil } func (a *Archive) load(key string) ([]Receipt, error) { data, err := a.db.GetMarker(key) if err != nil || len(data) == 0 { return nil, nil } var rs []Receipt if err = json.Unmarshal(data, &rs); err != nil { return nil, fmt.Errorf("receipts: corrupt bucket %s: %w", key, err) } return rs, nil } func (a *Archive) store(key string, v any) error { b, err := json.Marshal(v) if err != nil { return err } return a.db.SetMarker(key, b) } // Totals is the exact accounting for one asset, host, and period. type Totals struct { AssetID string `json:"asset"` Host string `json:"host"` Period string `json:"period"` Plays int64 `json:"plays"` Downloads int64 `json:"downloads"` Bytes int64 `json:"bytes"` Sats int64 `json:"sats"` Listeners int64 `json:"listeners"` } // Compute recomputes totals from receipts. It is deterministic: the same input // always produces the same Totals. func Compute(rs []Receipt, assetID, host, period string) Totals { t := Totals{AssetID: assetID, Host: host, Period: period} buyers := make(map[string]struct{}) for i := range rs { r := &rs[i] if host != "" && r.Server != host { continue } if r.Mode == ModeStream { t.Plays++ } else { t.Downloads++ } t.Bytes += r.BytesN() t.Sats += r.Sats() if r.Buyer != "" { buyers[r.Buyer] = struct{}{} } } t.Listeners = int64(len(buyers)) return t } // PublishAggregate builds and signs an immutable kind 32219 aggregate. func PublishAggregate(sign signer.I, t Totals) (*event.E, error) { if !deed.IsAssetID(t.AssetID) { return nil, fmt.Errorf("receipts: invalid asset id") } if t.Period == "" { return nil, fmt.Errorf("receipts: aggregate needs a period") } body, err := json.Marshal(t) if err != nil { return nil, err } ev := event.New() ev.Kind = kind.HostAggregate.ToU16() ev.CreatedAt = timestamp.Now().I64() ev.Tags = tag.NewS() ev.Tags.Append(tag.NewFromBytesSlice([]byte(deed.TagAsset), []byte(t.AssetID))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("period"), []byte(t.Period))) if t.Host != "" { ev.Tags.Append(tag.NewFromBytesSlice([]byte("server"), []byte(t.Host))) } ev.Tags.Append(tag.NewFromBytesSlice([]byte("plays"), []byte(strconv.FormatInt(t.Plays, 10)))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("downloads"), []byte(strconv.FormatInt(t.Downloads, 10)))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("bytes"), []byte(strconv.FormatInt(t.Bytes, 10)))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("sats"), []byte(strconv.FormatInt(t.Sats, 10)))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("listeners"), []byte(strconv.FormatInt(t.Listeners, 10)))) ev.Content = body if err = ev.Sign(sign); err != nil { return nil, fmt.Errorf("receipts: sign aggregate: %w", err) } return ev, nil } // Rollup sums surviving host aggregates and signs a kind 32220 that references // each one by e tag. A deleted aggregate therefore drops out of both the sum and // the reference list. func Rollup(sign signer.I, assetID, period, publisher string, ownReceipts int64, aggregates []*event.E) (*event.E, error) { if !deed.IsAssetID(assetID) { return nil, fmt.Errorf("receipts: invalid asset id") } var t Totals t.AssetID = assetID t.Period = period hosts := make([]string, 0, len(aggregates)) for _, ev := range aggregates { if ev == nil || ev.Kind != kind.HostAggregate.ToU16() { continue } if tagVal(ev, deed.TagAsset) != assetID || tagVal(ev, "period") != period { continue } t.Plays += parseInt(tagVal(ev, "plays")) t.Downloads += parseInt(tagVal(ev, "downloads")) t.Bytes += parseInt(tagVal(ev, "bytes")) t.Sats += parseInt(tagVal(ev, "sats")) t.Listeners += parseInt(tagVal(ev, "listeners")) if h := tagVal(ev, "server"); h != "" { hosts = append(hosts, h) } } sort.Strings(hosts) body, err := json.Marshal(map[string]any{ "asset": assetID, "period": period, "publisher": publisher, "hosts": hosts, "plays": t.Plays, "downloads": t.Downloads, "bytes": t.Bytes, "sats": t.Sats, "listeners": t.Listeners, "receipts": ownReceipts, }) if err != nil { return nil, err } ev := event.New() ev.Kind = kind.PublisherRollup.ToU16() ev.CreatedAt = timestamp.Now().I64() ev.Tags = tag.NewS() ev.Tags.Append(tag.NewFromBytesSlice([]byte(deed.TagAsset), []byte(assetID))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("period"), []byte(period))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("receipts"), []byte(strconv.FormatInt(ownReceipts, 10)))) for _, agg := range aggregates { if agg == nil { continue } ev.Tags.Append(tag.NewFromBytesSlice([]byte("e"), agg.ID)) } ev.Content = body if err = ev.Sign(sign); err != nil { return nil, fmt.Errorf("receipts: sign rollup: %w", err) } return ev, nil } func tagVal(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 parseInt(s string) int64 { n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64) return n }