// Package catalog answers one question for the gate and the receipt issuer: // which asset is this blob? // // A track (32210), album (32211), or standalone edition (32216) carries one // "x" tag per published encoding. Every encoding of one recording resolves to // the same asset id, so a re-encode changes the blob but not the entitlement. package catalog import ( "context" "encoding/hex" "fmt" "strings" "sync" "time" "git.smesh.lol/orly/pkg/database" "git.smesh.lol/orly/pkg/musiquay/deed" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/filter" "git.smesh.lol/orly/pkg/nostr/encoders/kind" "git.smesh.lol/orly/pkg/nostr/encoders/tag" ) // Ref is a resolved asset reference. type Ref struct { // AssetID is the stable asset id. AssetID string // Coordinate is the addressable coordinate "kind:pubkey:d". Coordinate string // Kind is the asset event kind. Kind uint16 // Author is the asset event author. Author []byte // Event is the asset event that named the blob. Event *event.E // Blob is the requested blob hash. Blob string } // Resolver maps a blob hash to the asset event that published it. type Resolver struct { db database.Database mu sync.RWMutex cache map[string]Ref maxSize int now func() time.Time } // NewResolver creates a resolver backed by the relay database. Because Blossom // and the relay are co-located in the reference deployment, the query is local: // no WebSocket hop and no second index service. func NewResolver(db database.Database) *Resolver { return &Resolver{ db: db, cache: make(map[string]Ref), maxSize: 10000, now: time.Now, } } // SetMaxSize bounds the in-process cache. func (r *Resolver) SetMaxSize(n int) { if n > 0 { r.mu.Lock() r.maxSize = n r.mu.Unlock() } } // Resolve returns the asset that published a blob hash. func (r *Resolver) Resolve(ctx context.Context, blobHex string) (*Ref, error) { blobHex = strings.ToLower(strings.TrimSpace(blobHex)) if len(blobHex) != 64 { return nil, fmt.Errorf("catalog: blob hash must be 64 hex characters") } if _, err := hex.DecodeString(blobHex); err != nil { return nil, fmt.Errorf("catalog: blob hash is not hex: %w", err) } r.mu.RLock() ref, ok := r.cache[blobHex] r.mu.RUnlock() if ok { return &ref, nil } f := filter.New() f.Kinds = kind.NewS(kind.Track, kind.Album, kind.Edition) f.Tags = tag.NewS(tag.NewFromBytesSlice([]byte("x"), []byte(blobHex))) f.Limit = new(uint) *f.Limit = 8 evs, err := r.db.QueryEvents(ctx, f) if err != nil { return nil, fmt.Errorf("catalog: query blob %s: %w", blobHex, err) } if len(evs) == 0 { return nil, fmt.Errorf("catalog: no asset publishes blob %s", blobHex) } // Prefer an event that actually carries the blob in an x tag (the index // guarantees it, but a relay bug must not silently mis-resolve) and, among // those, the newest. var best *event.E for _, ev := range evs { if ev == nil || !hasXTag(ev, blobHex) { continue } if best == nil || ev.CreatedAt > best.CreatedAt { best = ev } } if best == nil { return nil, fmt.Errorf("catalog: indexed event does not carry blob %s", blobHex) } ref, err = r.refFromEvent(best, blobHex) if err != nil { return nil, err } r.mu.Lock() if len(r.cache) >= r.maxSize { // Drop one arbitrary entry: the cache is a fast path, not a store. for k := range r.cache { delete(r.cache, k) break } } r.cache[blobHex] = ref r.mu.Unlock() return &ref, nil } // Observe warms the cache from a saved event. It is called from the relay's // post-save hook for 32210/32211/32216 events. func (r *Resolver) Observe(ev *event.E) { if ev == nil { return } switch ev.Kind { case kind.Track.ToU16(), kind.Album.ToU16(), kind.Edition.ToU16(): default: return } for _, t := range ev.Tags.GetAll([]byte("x")) { blob := strings.ToLower(string(t.Value())) if len(blob) != 64 { continue } ref, err := r.refFromEvent(ev, blob) if err != nil { continue } r.mu.Lock() if len(r.cache) >= r.maxSize { for k := range r.cache { delete(r.cache, k) break } } r.cache[blob] = ref r.mu.Unlock() } } // Invalidate drops a blob entry. func (r *Resolver) Invalidate(blobHex string) { r.mu.Lock() delete(r.cache, strings.ToLower(blobHex)) r.mu.Unlock() } func (r *Resolver) refFromEvent(ev *event.E, blobHex string) (Ref, error) { assetID := tagValue(ev, deed.TagAsset) if assetID == "" { // A publication that predates the asset tag still has a derivable id: // the first event for the asset is the one that is being resolved only // when it is the first, which the caller cannot know here. Deriving from // this event is correct for the first publication; for a later event the // asset tag is mandatory. Refusing a later untagged event is safer than // inventing a second id for the same recording. derived, err := deed.DeriveAssetID(ev.ID) if err != nil { return Ref{}, err } assetID = derived } if !deed.IsAssetID(assetID) { return Ref{}, fmt.Errorf("catalog: asset tag %q is invalid", assetID) } d := tagValue(ev, "d") if d == "" { return Ref{}, fmt.Errorf("catalog: asset event %x has no d tag", ev.ID) } coord := fmt.Sprintf("%d:%s:%s", ev.Kind, hex.EncodeToString(ev.Pubkey), d) return Ref{ AssetID: assetID, Coordinate: coord, Kind: ev.Kind, Author: append([]byte(nil), ev.Pubkey...), Event: ev, Blob: blobHex, }, nil } func hasXTag(ev *event.E, blobHex string) bool { for _, t := range ev.Tags.GetAll([]byte("x")) { if strings.EqualFold(string(t.Value()), blobHex) { return true } } return false } 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()) }