1 // Package catalog answers one question for the gate and the receipt issuer:
2 // which asset is this blob?
3 //
4 // A track (32210), album (32211), or standalone edition (32216) carries one
5 // "x" tag per published encoding. Every encoding of one recording resolves to
6 // the same asset id, so a re-encode changes the blob but not the entitlement.
7 package catalog
8 9 import (
10 "context"
11 "encoding/hex"
12 "fmt"
13 "strings"
14 "sync"
15 "time"
16 17 "git.smesh.lol/orly/pkg/database"
18 "git.smesh.lol/orly/pkg/musiquay/deed"
19 "git.smesh.lol/orly/pkg/nostr/encoders/event"
20 "git.smesh.lol/orly/pkg/nostr/encoders/filter"
21 "git.smesh.lol/orly/pkg/nostr/encoders/kind"
22 "git.smesh.lol/orly/pkg/nostr/encoders/tag"
23 )
24 25 // Ref is a resolved asset reference.
26 type Ref struct {
27 // AssetID is the stable asset id.
28 AssetID string
29 // Coordinate is the addressable coordinate "kind:pubkey:d".
30 Coordinate string
31 // Kind is the asset event kind.
32 Kind uint16
33 // Author is the asset event author.
34 Author []byte
35 // Event is the asset event that named the blob.
36 Event *event.E
37 // Blob is the requested blob hash.
38 Blob string
39 }
40 41 // Resolver maps a blob hash to the asset event that published it.
42 type Resolver struct {
43 db database.Database
44 45 mu sync.RWMutex
46 cache map[string]Ref
47 maxSize int
48 now func() time.Time
49 }
50 51 // NewResolver creates a resolver backed by the relay database. Because Blossom
52 // and the relay are co-located in the reference deployment, the query is local:
53 // no WebSocket hop and no second index service.
54 func NewResolver(db database.Database) *Resolver {
55 return &Resolver{
56 db: db,
57 cache: make(map[string]Ref),
58 maxSize: 10000,
59 now: time.Now,
60 }
61 }
62 63 // SetMaxSize bounds the in-process cache.
64 func (r *Resolver) SetMaxSize(n int) {
65 if n > 0 {
66 r.mu.Lock()
67 r.maxSize = n
68 r.mu.Unlock()
69 }
70 }
71 72 // Resolve returns the asset that published a blob hash.
73 func (r *Resolver) Resolve(ctx context.Context, blobHex string) (*Ref, error) {
74 blobHex = strings.ToLower(strings.TrimSpace(blobHex))
75 if len(blobHex) != 64 {
76 return nil, fmt.Errorf("catalog: blob hash must be 64 hex characters")
77 }
78 if _, err := hex.DecodeString(blobHex); err != nil {
79 return nil, fmt.Errorf("catalog: blob hash is not hex: %w", err)
80 }
81 82 r.mu.RLock()
83 ref, ok := r.cache[blobHex]
84 r.mu.RUnlock()
85 if ok {
86 return &ref, nil
87 }
88 89 f := filter.New()
90 f.Kinds = kind.NewS(kind.Track, kind.Album, kind.Edition)
91 f.Tags = tag.NewS(tag.NewFromBytesSlice([]byte("x"), []byte(blobHex)))
92 f.Limit = new(uint)
93 *f.Limit = 8
94 95 evs, err := r.db.QueryEvents(ctx, f)
96 if err != nil {
97 return nil, fmt.Errorf("catalog: query blob %s: %w", blobHex, err)
98 }
99 if len(evs) == 0 {
100 return nil, fmt.Errorf("catalog: no asset publishes blob %s", blobHex)
101 }
102 103 // Prefer an event that actually carries the blob in an x tag (the index
104 // guarantees it, but a relay bug must not silently mis-resolve) and, among
105 // those, the newest.
106 var best *event.E
107 for _, ev := range evs {
108 if ev == nil || !hasXTag(ev, blobHex) {
109 continue
110 }
111 if best == nil || ev.CreatedAt > best.CreatedAt {
112 best = ev
113 }
114 }
115 if best == nil {
116 return nil, fmt.Errorf("catalog: indexed event does not carry blob %s", blobHex)
117 }
118 119 ref, err = r.refFromEvent(best, blobHex)
120 if err != nil {
121 return nil, err
122 }
123 r.mu.Lock()
124 if len(r.cache) >= r.maxSize {
125 // Drop one arbitrary entry: the cache is a fast path, not a store.
126 for k := range r.cache {
127 delete(r.cache, k)
128 break
129 }
130 }
131 r.cache[blobHex] = ref
132 r.mu.Unlock()
133 return &ref, nil
134 }
135 136 // Observe warms the cache from a saved event. It is called from the relay's
137 // post-save hook for 32210/32211/32216 events.
138 func (r *Resolver) Observe(ev *event.E) {
139 if ev == nil {
140 return
141 }
142 switch ev.Kind {
143 case kind.Track.ToU16(), kind.Album.ToU16(), kind.Edition.ToU16():
144 default:
145 return
146 }
147 for _, t := range ev.Tags.GetAll([]byte("x")) {
148 blob := strings.ToLower(string(t.Value()))
149 if len(blob) != 64 {
150 continue
151 }
152 ref, err := r.refFromEvent(ev, blob)
153 if err != nil {
154 continue
155 }
156 r.mu.Lock()
157 if len(r.cache) >= r.maxSize {
158 for k := range r.cache {
159 delete(r.cache, k)
160 break
161 }
162 }
163 r.cache[blob] = ref
164 r.mu.Unlock()
165 }
166 }
167 168 // Invalidate drops a blob entry.
169 func (r *Resolver) Invalidate(blobHex string) {
170 r.mu.Lock()
171 delete(r.cache, strings.ToLower(blobHex))
172 r.mu.Unlock()
173 }
174 175 func (r *Resolver) refFromEvent(ev *event.E, blobHex string) (Ref, error) {
176 assetID := tagValue(ev, deed.TagAsset)
177 if assetID == "" {
178 // A publication that predates the asset tag still has a derivable id:
179 // the first event for the asset is the one that is being resolved only
180 // when it is the first, which the caller cannot know here. Deriving from
181 // this event is correct for the first publication; for a later event the
182 // asset tag is mandatory. Refusing a later untagged event is safer than
183 // inventing a second id for the same recording.
184 derived, err := deed.DeriveAssetID(ev.ID)
185 if err != nil {
186 return Ref{}, err
187 }
188 assetID = derived
189 }
190 if !deed.IsAssetID(assetID) {
191 return Ref{}, fmt.Errorf("catalog: asset tag %q is invalid", assetID)
192 }
193 d := tagValue(ev, "d")
194 if d == "" {
195 return Ref{}, fmt.Errorf("catalog: asset event %x has no d tag", ev.ID)
196 }
197 coord := fmt.Sprintf("%d:%s:%s", ev.Kind, hex.EncodeToString(ev.Pubkey), d)
198 return Ref{
199 AssetID: assetID,
200 Coordinate: coord,
201 Kind: ev.Kind,
202 Author: append([]byte(nil), ev.Pubkey...),
203 Event: ev,
204 Blob: blobHex,
205 }, nil
206 }
207 208 func hasXTag(ev *event.E, blobHex string) bool {
209 for _, t := range ev.Tags.GetAll([]byte("x")) {
210 if strings.EqualFold(string(t.Value()), blobHex) {
211 return true
212 }
213 }
214 return false
215 }
216 217 func tagValue(ev *event.E, name string) string {
218 if ev == nil || ev.Tags == nil {
219 return ""
220 }
221 t := ev.Tags.GetFirst([]byte(name))
222 if t == nil {
223 return ""
224 }
225 return string(t.Value())
226 }
227