access.go raw
1 // Package access fetches, verifies, caches, and refreshes the exact membership
2 // sets that gate paid musiquay assets.
3 //
4 // The set is a performance cache in front of the durable deed, not the
5 // entitlement itself. Losing it degrades the fast path; it never invalidates a
6 // purchase. The manager therefore fails closed only for the set path: an
7 // unparseable or unverifiable set refuses service rather than granting it, and
8 // the gate can still honour a valid deed.
9 package access
10
11 import (
12 "bytes"
13 "context"
14 "crypto/sha256"
15 "encoding/hex"
16 "fmt"
17 "strconv"
18 "strings"
19 "sync"
20 "time"
21
22 "git.smesh.lol/orly/pkg/database"
23 "git.smesh.lol/orly/pkg/musiquay/gcs"
24 "git.smesh.lol/orly/pkg/nostr/encoders/event"
25 "git.smesh.lol/orly/pkg/nostr/encoders/filter"
26 "git.smesh.lol/orly/pkg/nostr/encoders/kind"
27 "git.smesh.lol/orly/pkg/nostr/encoders/tag"
28 )
29
30 // BlobFetcher returns the bytes of a Blossom blob by hex hash. When Blossom and
31 // the relay are in one process this reads local storage; a remote host passes an
32 // HTTP-backed fetcher.
33 type BlobFetcher func(ctx context.Context, sha256Hex string) ([]byte, error)
34
35 // Filter is a verified membership set.
36 type Filter struct {
37 // Event is the 32217 event that published the set.
38 Event *event.E
39 // D is the event's d tag.
40 D string
41 // AssetAddress is the address the set is bound to, e.g.
42 // "32210:<owner>:<track-d>".
43 AssetAddress string
44 // BlobX is the set blob hash.
45 BlobX string
46 // Set is the decoded exact set.
47 Set *gcs.Set
48 // FetchedAt is when the set was fetched.
49 FetchedAt time.Time
50 }
51
52 // Tier returns "fan", "retail", or "sub" from the d tag.
53 func (f *Filter) Tier() string {
54 if f == nil {
55 return ""
56 }
57 if i := strings.IndexByte(f.D, ':'); i > 0 {
58 return f.D[:i]
59 }
60 return ""
61 }
62
63 // Manager resolves filters from the relay database and Blossom.
64 type Manager struct {
65 db database.Database
66 fetch BlobFetcher
67
68 mu sync.Mutex
69 cache map[string]*cacheEntry
70 ttl time.Duration
71 now func() time.Time
72 }
73
74 type cacheEntry struct {
75 filter *Filter
76 // blobX is the blob hash the cached set came from, for delta matching.
77 blobX string
78 // at is the cache insertion time.
79 at time.Time
80 // dirty marks an entry whose event has been replaced. The set is kept so
81 // the delta path can still use it as a parent; a dirty entry is never
82 // served without re-resolving the event.
83 dirty bool
84 }
85
86 // New creates a manager. fetch must not be nil for a priced asset; a nil
87 // fetcher makes every priced lookup fail closed.
88 func New(db database.Database, fetch BlobFetcher) *Manager {
89 return &Manager{
90 db: db,
91 fetch: fetch,
92 cache: make(map[string]*cacheEntry),
93 ttl: 5 * time.Minute,
94 now: time.Now,
95 }
96 }
97
98 // SetTTL controls how long a verified set is reused. A replacement event
99 // invalidates it immediately through Observe.
100 func (m *Manager) SetTTL(d time.Duration) {
101 if d > 0 {
102 m.ttl = d
103 }
104 }
105
106 // Observe invalidates the cache for a newly saved 32217 event.
107 func (m *Manager) Observe(ev *event.E) {
108 if ev == nil || ev.Kind != kind.AccessFilter.ToU16() {
109 return
110 }
111 d := tagValue(ev, "d")
112 if d == "" {
113 return
114 }
115 m.mu.Lock()
116 for k, e := range m.cache {
117 if strings.HasSuffix(k, ":"+hex.EncodeToString(ev.Pubkey)+":"+d) {
118 // Keep the set: it is the parent a delta blob will name. Marking it
119 // dirty forces the next lookup to re-resolve the event.
120 e.dirty = true
121 }
122 }
123 m.mu.Unlock()
124 }
125
126 // Lookup returns the current filter for an owner and d tag.
127 //
128 // A missing filter is not an error: it means the asset is free under the
129 // protocol rule that an asset is free if and only if no filter exists. A
130 // present but invalid filter is an error, and the caller must refuse service.
131 func (m *Manager) Lookup(ctx context.Context, owner []byte, d string) (*Filter, error) {
132 key := filterKey(owner, d)
133 m.mu.Lock()
134 e := m.cache[key]
135 m.mu.Unlock()
136 if e != nil && !e.dirty && m.now().Sub(e.at) < m.ttl {
137 return e.filter, nil
138 }
139
140 f := filter.New()
141 f.Kinds = kind.NewS(kind.AccessFilter)
142 f.Authors = tag.NewFromBytesSlice(owner)
143 f.Tags = tag.NewS(tag.NewFromBytesSlice([]byte("d"), []byte(d)))
144 f.Limit = new(uint)
145 *f.Limit = 4
146 evs, err := m.db.QueryEvents(ctx, f)
147 if err != nil {
148 return nil, fmt.Errorf("access: query filter %s: %w", d, err)
149 }
150 var best *event.E
151 for _, ev := range evs {
152 if ev == nil || tagValue(ev, "d") != d {
153 continue
154 }
155 if best == nil || ev.CreatedAt > best.CreatedAt {
156 best = ev
157 }
158 }
159 if best == nil {
160 return nil, nil
161 }
162 if valid, verr := best.Verify(); verr != nil || !valid {
163 return nil, fmt.Errorf("access: filter event signature invalid")
164 }
165 if exp := tagValue(best, "expiration"); exp != "" {
166 if n, err := strconv.ParseInt(exp, 10, 64); err == nil && n <= m.now().Unix() {
167 // An expired subscription set covers nobody.
168 return nil, nil
169 }
170 }
171
172 filt, err := m.build(ctx, best, e)
173 if err != nil {
174 return nil, err
175 }
176 m.mu.Lock()
177 m.cache[key] = &cacheEntry{filter: filt, blobX: filt.BlobX, at: m.now()}
178 m.mu.Unlock()
179 return filt, nil
180 }
181
182 // IsMember reports whether a pubkey is in the owner's set.
183 func (m *Manager) IsMember(ctx context.Context, owner []byte, d string, pubkey []byte) (bool, error) {
184 f, err := m.Lookup(ctx, owner, d)
185 if err != nil {
186 return false, err
187 }
188 if f == nil || f.Set == nil {
189 return false, nil
190 }
191 return f.Set.Contains(pubkey), nil
192 }
193
194 // build verifies the event parameters against the blob and decodes the set.
195 func (m *Manager) build(ctx context.Context, ev *event.E, cached *cacheEntry) (*Filter, error) {
196 if tagValue(ev, "filter") != "gcs" {
197 return nil, fmt.Errorf("access: filter %s does not declare gcs", tagValue(ev, "d"))
198 }
199 x := strings.ToLower(tagValue(ev, "x"))
200 if len(x) != 64 {
201 return nil, fmt.Errorf("access: filter %s has no valid x tag", tagValue(ev, "d"))
202 }
203 wantN, err := strconv.ParseUint(tagValue(ev, "n"), 10, 64)
204 if err != nil {
205 return nil, fmt.Errorf("access: filter %s has no valid n tag", tagValue(ev, "d"))
206 }
207 wantHash, err := strconv.Atoi(tagValue(ev, "hash"))
208 if err != nil || wantHash <= 0 {
209 return nil, fmt.Errorf("access: filter %s has no valid hash tag", tagValue(ev, "d"))
210 }
211 d := tagValue(ev, "d")
212 assetAddr := strings.TrimPrefix(strings.TrimPrefix(d, "fan:"), "retail:")
213 if assetAddr == d {
214 // sub: sets are addressed by the retailer's channel, not by an asset.
215 assetAddr = d
216 }
217
218 if m.fetch == nil {
219 return nil, fmt.Errorf("access: no blob fetcher")
220 }
221
222 var blob []byte
223 if cached != nil && cached.blobX != "" && tagValue(ev, "prev") == cached.blobX {
224 // Delta path: fetch only the additions, then merge with the cached set.
225 dx := strings.ToLower(tagValue(ev, "delta"))
226 if len(dx) == 64 {
227 delta, derr := m.fetch(ctx, dx)
228 if derr == nil {
229 if baseX, xerr := gcs.DeltaBaseX(delta); xerr == nil && hex.EncodeToString(baseX) == cached.blobX {
230 added, aerr := gcs.ApplyDelta(cached.filter.Set, delta)
231 if aerr == nil {
232 merged, merr := gcs.MergeHashes(cached.filter.Set, added)
233 if merr == nil {
234 if serr := checkParams(merged, ev, wantN, wantHash); serr != nil {
235 return nil, serr
236 }
237 return &Filter{
238 Event: ev, D: d, AssetAddress: assetAddr,
239 BlobX: x, Set: merged, FetchedAt: m.now(),
240 }, nil
241 }
242 }
243 }
244 }
245 // A bad delta falls through to the full blob.
246 }
247 }
248
249 blob, err = m.fetch(ctx, x)
250 if err != nil {
251 return nil, fmt.Errorf("access: fetch filter blob %s: %w", x, err)
252 }
253 sum := sha256.Sum256(blob)
254 if hex.EncodeToString(sum[:]) != x {
255 return nil, fmt.Errorf("access: filter blob %s does not match its x tag", x)
256 }
257 set, err := gcs.Parse(blob)
258 if err != nil {
259 return nil, fmt.Errorf("access: parse filter blob %s: %w", x, err)
260 }
261 if set.Asset != assetAddr {
262 return nil, fmt.Errorf("access: set is bound to %q, event names %q", set.Asset, assetAddr)
263 }
264 if err = checkParams(set, ev, wantN, wantHash); err != nil {
265 return nil, err
266 }
267 return &Filter{Event: ev, D: d, AssetAddress: assetAddr, BlobX: x, Set: set, FetchedAt: m.now()}, nil
268 }
269
270 // checkParams cross-checks the decoded header against the event.
271 func checkParams(set *gcs.Set, ev *event.E, wantN uint64, wantHash int) error {
272 if set.N != wantN {
273 return fmt.Errorf("access: set has %d elements, event says %d", set.N, wantN)
274 }
275 if set.HashWidth != wantHash {
276 return fmt.Errorf("access: set hash width %d, event says %d", set.HashWidth, wantHash)
277 }
278 return nil
279 }
280
281 func filterKey(owner []byte, d string) string {
282 return fmt.Sprintf("%d:%s:%s", kind.AccessFilter.ToU16(), hex.EncodeToString(owner), d)
283 }
284
285 // BuildFilterEvent constructs a 32217 event for a set that has already been
286 // uploaded to Blossom.
287 type BuildOptions struct {
288 Owner []byte
289 D string
290 X string
291 N uint64
292 HashWidth int
293 Prev string
294 Delta string
295 Server string
296 Mints []string
297 Retailers [][]byte
298 // Channel is the subscription channel a sub: set covers.
299 Channel string
300 // Catalog lists the asset addresses a subscription covers.
301 Catalog []string
302 Expiration int64
303 }
304
305 // BuildEvent returns the unsigned 32217 event; the caller signs it.
306 func BuildEvent(o BuildOptions) (*event.E, error) {
307 if len(o.Owner) != 32 {
308 return nil, fmt.Errorf("access: owner must be a 32-byte pubkey")
309 }
310 if o.D == "" {
311 return nil, fmt.Errorf("access: filter needs a d tag")
312 }
313 if len(o.X) != 64 {
314 return nil, fmt.Errorf("access: filter needs a blob x")
315 }
316 ev := event.New()
317 ev.Kind = kind.AccessFilter.ToU16()
318 ev.Tags = tag.NewS()
319 ev.Tags.Append(tag.NewFromBytesSlice([]byte("d"), []byte(o.D)))
320 ev.Tags.Append(tag.NewFromBytesSlice([]byte("filter"), []byte("gcs")))
321 ev.Tags.Append(tag.NewFromBytesSlice([]byte("n"), []byte(strconv.FormatUint(o.N, 10))))
322 ev.Tags.Append(tag.NewFromBytesSlice([]byte("hash"), []byte(strconv.Itoa(o.HashWidth))))
323 ev.Tags.Append(tag.NewFromBytesSlice([]byte("x"), []byte(o.X)))
324 if o.Prev != "" {
325 ev.Tags.Append(tag.NewFromBytesSlice([]byte("prev"), []byte(o.Prev)))
326 }
327 if o.Delta != "" {
328 ev.Tags.Append(tag.NewFromBytesSlice([]byte("delta"), []byte(o.Delta)))
329 }
330 if o.Server != "" {
331 ev.Tags.Append(tag.NewFromBytesSlice([]byte("server"), []byte(o.Server)))
332 }
333 if o.Channel != "" {
334 ev.Tags.Append(tag.NewFromBytesSlice([]byte("channel"), []byte(o.Channel)))
335 }
336 for _, addr := range o.Catalog {
337 ev.Tags.Append(tag.NewFromBytesSlice([]byte("catalog"), []byte(addr)))
338 }
339 for _, m := range o.Mints {
340 ev.Tags.Append(tag.NewFromBytesSlice([]byte("mint"), []byte(m)))
341 }
342 for _, r := range o.Retailers {
343 ev.Tags.Append(tag.NewFromBytesSlice([]byte("retailer"), []byte(hex.EncodeToString(r))))
344 }
345 if o.Expiration != 0 {
346 ev.Tags.Append(tag.NewFromBytesSlice([]byte("expiration"), []byte(strconv.FormatInt(o.Expiration, 10))))
347 }
348 return ev, nil
349 }
350
351 func tagValue(ev *event.E, name string) string {
352 if ev == nil || ev.Tags == nil {
353 return ""
354 }
355 t := ev.Tags.GetFirst([]byte(name))
356 if t == nil {
357 return ""
358 }
359 return string(t.Value())
360 }
361
362 // Element is the domain-tagged element hash, exposed so callers can test a
363 // membership decision without a set.
364 func Element(pubkey []byte, hashWidth int) []byte { return gcs.Element(pubkey, hashWidth) }
365
366 // EqualSet reports whether two sets encode identically.
367 func EqualSet(a, b *gcs.Set) bool {
368 if a == nil || b == nil {
369 return a == b
370 }
371 ab, err := a.Marshal()
372 if err != nil {
373 return false
374 }
375 bb, err := b.Marshal()
376 if err != nil {
377 return false
378 }
379 return bytes.Equal(ab, bb)
380 }
381