// Package access fetches, verifies, caches, and refreshes the exact membership // sets that gate paid musiquay assets. // // The set is a performance cache in front of the durable deed, not the // entitlement itself. Losing it degrades the fast path; it never invalidates a // purchase. The manager therefore fails closed only for the set path: an // unparseable or unverifiable set refuses service rather than granting it, and // the gate can still honour a valid deed. package access import ( "bytes" "context" "crypto/sha256" "encoding/hex" "fmt" "strconv" "strings" "sync" "time" "git.smesh.lol/orly/pkg/database" "git.smesh.lol/orly/pkg/musiquay/gcs" "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" ) // BlobFetcher returns the bytes of a Blossom blob by hex hash. When Blossom and // the relay are in one process this reads local storage; a remote host passes an // HTTP-backed fetcher. type BlobFetcher func(ctx context.Context, sha256Hex string) ([]byte, error) // Filter is a verified membership set. type Filter struct { // Event is the 32217 event that published the set. Event *event.E // D is the event's d tag. D string // AssetAddress is the address the set is bound to, e.g. // "32210::". AssetAddress string // BlobX is the set blob hash. BlobX string // Set is the decoded exact set. Set *gcs.Set // FetchedAt is when the set was fetched. FetchedAt time.Time } // Tier returns "fan", "retail", or "sub" from the d tag. func (f *Filter) Tier() string { if f == nil { return "" } if i := strings.IndexByte(f.D, ':'); i > 0 { return f.D[:i] } return "" } // Manager resolves filters from the relay database and Blossom. type Manager struct { db database.Database fetch BlobFetcher mu sync.Mutex cache map[string]*cacheEntry ttl time.Duration now func() time.Time } type cacheEntry struct { filter *Filter // blobX is the blob hash the cached set came from, for delta matching. blobX string // at is the cache insertion time. at time.Time // dirty marks an entry whose event has been replaced. The set is kept so // the delta path can still use it as a parent; a dirty entry is never // served without re-resolving the event. dirty bool } // New creates a manager. fetch must not be nil for a priced asset; a nil // fetcher makes every priced lookup fail closed. func New(db database.Database, fetch BlobFetcher) *Manager { return &Manager{ db: db, fetch: fetch, cache: make(map[string]*cacheEntry), ttl: 5 * time.Minute, now: time.Now, } } // SetTTL controls how long a verified set is reused. A replacement event // invalidates it immediately through Observe. func (m *Manager) SetTTL(d time.Duration) { if d > 0 { m.ttl = d } } // Observe invalidates the cache for a newly saved 32217 event. func (m *Manager) Observe(ev *event.E) { if ev == nil || ev.Kind != kind.AccessFilter.ToU16() { return } d := tagValue(ev, "d") if d == "" { return } m.mu.Lock() for k, e := range m.cache { if strings.HasSuffix(k, ":"+hex.EncodeToString(ev.Pubkey)+":"+d) { // Keep the set: it is the parent a delta blob will name. Marking it // dirty forces the next lookup to re-resolve the event. e.dirty = true } } m.mu.Unlock() } // Lookup returns the current filter for an owner and d tag. // // A missing filter is not an error: it means the asset is free under the // protocol rule that an asset is free if and only if no filter exists. A // present but invalid filter is an error, and the caller must refuse service. func (m *Manager) Lookup(ctx context.Context, owner []byte, d string) (*Filter, error) { key := filterKey(owner, d) m.mu.Lock() e := m.cache[key] m.mu.Unlock() if e != nil && !e.dirty && m.now().Sub(e.at) < m.ttl { return e.filter, nil } f := filter.New() f.Kinds = kind.NewS(kind.AccessFilter) f.Authors = tag.NewFromBytesSlice(owner) f.Tags = tag.NewS(tag.NewFromBytesSlice([]byte("d"), []byte(d))) f.Limit = new(uint) *f.Limit = 4 evs, err := m.db.QueryEvents(ctx, f) if err != nil { return nil, fmt.Errorf("access: query filter %s: %w", d, err) } var best *event.E for _, ev := range evs { if ev == nil || tagValue(ev, "d") != d { continue } if best == nil || ev.CreatedAt > best.CreatedAt { best = ev } } if best == nil { return nil, nil } if valid, verr := best.Verify(); verr != nil || !valid { return nil, fmt.Errorf("access: filter event signature invalid") } if exp := tagValue(best, "expiration"); exp != "" { if n, err := strconv.ParseInt(exp, 10, 64); err == nil && n <= m.now().Unix() { // An expired subscription set covers nobody. return nil, nil } } filt, err := m.build(ctx, best, e) if err != nil { return nil, err } m.mu.Lock() m.cache[key] = &cacheEntry{filter: filt, blobX: filt.BlobX, at: m.now()} m.mu.Unlock() return filt, nil } // IsMember reports whether a pubkey is in the owner's set. func (m *Manager) IsMember(ctx context.Context, owner []byte, d string, pubkey []byte) (bool, error) { f, err := m.Lookup(ctx, owner, d) if err != nil { return false, err } if f == nil || f.Set == nil { return false, nil } return f.Set.Contains(pubkey), nil } // build verifies the event parameters against the blob and decodes the set. func (m *Manager) build(ctx context.Context, ev *event.E, cached *cacheEntry) (*Filter, error) { if tagValue(ev, "filter") != "gcs" { return nil, fmt.Errorf("access: filter %s does not declare gcs", tagValue(ev, "d")) } x := strings.ToLower(tagValue(ev, "x")) if len(x) != 64 { return nil, fmt.Errorf("access: filter %s has no valid x tag", tagValue(ev, "d")) } wantN, err := strconv.ParseUint(tagValue(ev, "n"), 10, 64) if err != nil { return nil, fmt.Errorf("access: filter %s has no valid n tag", tagValue(ev, "d")) } wantHash, err := strconv.Atoi(tagValue(ev, "hash")) if err != nil || wantHash <= 0 { return nil, fmt.Errorf("access: filter %s has no valid hash tag", tagValue(ev, "d")) } d := tagValue(ev, "d") assetAddr := strings.TrimPrefix(strings.TrimPrefix(d, "fan:"), "retail:") if assetAddr == d { // sub: sets are addressed by the retailer's channel, not by an asset. assetAddr = d } if m.fetch == nil { return nil, fmt.Errorf("access: no blob fetcher") } var blob []byte if cached != nil && cached.blobX != "" && tagValue(ev, "prev") == cached.blobX { // Delta path: fetch only the additions, then merge with the cached set. dx := strings.ToLower(tagValue(ev, "delta")) if len(dx) == 64 { delta, derr := m.fetch(ctx, dx) if derr == nil { if baseX, xerr := gcs.DeltaBaseX(delta); xerr == nil && hex.EncodeToString(baseX) == cached.blobX { added, aerr := gcs.ApplyDelta(cached.filter.Set, delta) if aerr == nil { merged, merr := gcs.MergeHashes(cached.filter.Set, added) if merr == nil { if serr := checkParams(merged, ev, wantN, wantHash); serr != nil { return nil, serr } return &Filter{ Event: ev, D: d, AssetAddress: assetAddr, BlobX: x, Set: merged, FetchedAt: m.now(), }, nil } } } } // A bad delta falls through to the full blob. } } blob, err = m.fetch(ctx, x) if err != nil { return nil, fmt.Errorf("access: fetch filter blob %s: %w", x, err) } sum := sha256.Sum256(blob) if hex.EncodeToString(sum[:]) != x { return nil, fmt.Errorf("access: filter blob %s does not match its x tag", x) } set, err := gcs.Parse(blob) if err != nil { return nil, fmt.Errorf("access: parse filter blob %s: %w", x, err) } if set.Asset != assetAddr { return nil, fmt.Errorf("access: set is bound to %q, event names %q", set.Asset, assetAddr) } if err = checkParams(set, ev, wantN, wantHash); err != nil { return nil, err } return &Filter{Event: ev, D: d, AssetAddress: assetAddr, BlobX: x, Set: set, FetchedAt: m.now()}, nil } // checkParams cross-checks the decoded header against the event. func checkParams(set *gcs.Set, ev *event.E, wantN uint64, wantHash int) error { if set.N != wantN { return fmt.Errorf("access: set has %d elements, event says %d", set.N, wantN) } if set.HashWidth != wantHash { return fmt.Errorf("access: set hash width %d, event says %d", set.HashWidth, wantHash) } return nil } func filterKey(owner []byte, d string) string { return fmt.Sprintf("%d:%s:%s", kind.AccessFilter.ToU16(), hex.EncodeToString(owner), d) } // BuildFilterEvent constructs a 32217 event for a set that has already been // uploaded to Blossom. type BuildOptions struct { Owner []byte D string X string N uint64 HashWidth int Prev string Delta string Server string Mints []string Retailers [][]byte // Channel is the subscription channel a sub: set covers. Channel string // Catalog lists the asset addresses a subscription covers. Catalog []string Expiration int64 } // BuildEvent returns the unsigned 32217 event; the caller signs it. func BuildEvent(o BuildOptions) (*event.E, error) { if len(o.Owner) != 32 { return nil, fmt.Errorf("access: owner must be a 32-byte pubkey") } if o.D == "" { return nil, fmt.Errorf("access: filter needs a d tag") } if len(o.X) != 64 { return nil, fmt.Errorf("access: filter needs a blob x") } ev := event.New() ev.Kind = kind.AccessFilter.ToU16() ev.Tags = tag.NewS() ev.Tags.Append(tag.NewFromBytesSlice([]byte("d"), []byte(o.D))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("filter"), []byte("gcs"))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("n"), []byte(strconv.FormatUint(o.N, 10)))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("hash"), []byte(strconv.Itoa(o.HashWidth)))) ev.Tags.Append(tag.NewFromBytesSlice([]byte("x"), []byte(o.X))) if o.Prev != "" { ev.Tags.Append(tag.NewFromBytesSlice([]byte("prev"), []byte(o.Prev))) } if o.Delta != "" { ev.Tags.Append(tag.NewFromBytesSlice([]byte("delta"), []byte(o.Delta))) } if o.Server != "" { ev.Tags.Append(tag.NewFromBytesSlice([]byte("server"), []byte(o.Server))) } if o.Channel != "" { ev.Tags.Append(tag.NewFromBytesSlice([]byte("channel"), []byte(o.Channel))) } for _, addr := range o.Catalog { ev.Tags.Append(tag.NewFromBytesSlice([]byte("catalog"), []byte(addr))) } for _, m := range o.Mints { ev.Tags.Append(tag.NewFromBytesSlice([]byte("mint"), []byte(m))) } for _, r := range o.Retailers { ev.Tags.Append(tag.NewFromBytesSlice([]byte("retailer"), []byte(hex.EncodeToString(r)))) } if o.Expiration != 0 { ev.Tags.Append(tag.NewFromBytesSlice([]byte("expiration"), []byte(strconv.FormatInt(o.Expiration, 10)))) } return ev, nil } 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()) } // Element is the domain-tagged element hash, exposed so callers can test a // membership decision without a set. func Element(pubkey []byte, hashWidth int) []byte { return gcs.Element(pubkey, hashWidth) } // EqualSet reports whether two sets encode identically. func EqualSet(a, b *gcs.Set) bool { if a == nil || b == nil { return a == b } ab, err := a.Marshal() if err != nil { return false } bb, err := b.Marshal() if err != nil { return false } return bytes.Equal(ab, bb) }