// Package filtercache reads compact filters from relays that cache them. // // It is the relay side of neutrino.FilterSource: the client asks for a range, // this asks the relays for the batches that cover it, decodes them, and hands // back the runs it got. Nothing it returns is trusted: neutrino verifies every // filter against the filter hash its own header chain commits to, so the relay's // position is the gateway's — it can deny service, not forge it. // // A cache miss is not an error. It is the normal answer for a range the relays // do not cover, and it falls through to the peer. package filtercache import ( "context" "crypto/rand" "errors" "fmt" "sort" "strings" "sync" "time" "git.smesh.lol/nostrino/pkg/cfevents" "git.smesh.lol/nostrino/pkg/neutrino" "git.smesh.lol/nostrino/pkg/nostr" "git.smesh.lol/nostrino/pkg/relay" ) // Config describes where the batches come from. type Config struct { // Chain is the chain name the batches are tagged with. Chain string // Relays are asked in order and the first that answers is used. Relays []string // Dial opens a relay transport. In a browser it is the page's WebSocket. Dial func(string) (relay.Transport, error) // Wait bounds one relay round trip: REQ, the stored events, EOSE. Wait time.Duration // Logf receives one line per answered window; nil discards them. Logf func(string, ...any) } // missReportEvery is how many consecutive empty windows pass between log lines. // // An empty window is a miss, which is normal: a cache starts where its sidecar // started and a wallet may scan below that. Giving up after a few misses would // be worse than the cost it saves, because the misses come first and the // coverage comes after: a wallet rescanning from an old swap height would pass // three uncovered windows and then never ask again, exactly where the cache // could have served it. One request per hundred blocks is a hundredth of what // the peer route costs, so asking every time is the cheap choice. const missReportEvery = 20 // Cache is a relay-backed filter source. One per chain. type Cache struct { cfg Config mu sync.Mutex clients map[string]*relay.Client // empty counts consecutive windows that came back with nothing. empty int } // New validates the configuration. It does not connect. func New(cfg Config) (*Cache, error) { if strings.TrimSpace(cfg.Chain) == "" { return nil, errors.New("filtercache: no chain") } if len(cfg.Relays) == 0 { return nil, errors.New("filtercache: no relay") } if cfg.Dial == nil { return nil, errors.New("filtercache: no transport") } if cfg.Wait <= 0 { // The wait covers one whole answer: the relay sends every stored // batch and then EOSE, so the bound is the transfer of up to a hundred // filters, not a round trip. At mainnet sizes that is nearly two // megabytes, and a five second bound would abandon the window on any // link slower than a few megabits, which would mean the cache and the // peer both doing the work. cfg.Wait = 30 * time.Second } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } return &Cache{cfg: cfg, clients: make(map[string]*relay.Client)}, nil } // Filters asks the relays for the batches covering [from,to]. // // The result is at most one window of work: neutrino bounds the range it asks // for, so this never accumulates a scan. func (c *Cache) Filters(ctx context.Context, from, to uint32) ([]neutrino.Filters, error) { if to < from { return nil, fmt.Errorf("filtercache: range %d..%d is reversed", from, to) } query := cfevents.Query(c.cfg.Chain, from, to) var failures []string for _, url := range c.cfg.Relays { runs, err := c.ask(ctx, url, query, from, to) if err != nil { failures = append(failures, url+": "+err.Error()) continue } c.report(from, to, runs) return runs, nil } if len(failures) > 0 { return nil, errors.New(strings.Join(failures, "; ")) } return nil, nil } // report logs one answered window and keeps the miss count, so a scan served // from the cache looks like one and a scan that is not says why. // // Exactly one line per window, because one window is one request: a caller that // counts these lines is counting what went over the wire. func (c *Cache) report(from, to uint32, runs []neutrino.Filters) { if len(runs) == 0 { c.mu.Lock() c.empty++ misses := c.empty c.mu.Unlock() if misses == 1 || misses%missReportEvery == 0 { c.cfg.Logf("filtercache: no batch for %d..%d (%d in a row)", from, to, misses) } return } c.mu.Lock() c.empty = 0 c.mu.Unlock() filters := 0 for _, run := range runs { filters += len(run.Filters) } c.cfg.Logf("filtercache: %d batches holding %d filters for %d..%d", len(runs), filters, from, to) } // ask runs one REQ against one relay and returns the batches it holds. func (c *Cache) ask(ctx context.Context, url string, query nostr.Filter, from, to uint32) ([]neutrino.Filters, error) { client, err := c.client(url) if err != nil { return nil, err } sub, err := client.Subscribe(query) if err != nil { return nil, err } defer sub.Close() waitCtx, cancel := context.WithTimeout(ctx, c.cfg.Wait) defer cancel() if err := client.WaitEOSE(waitCtx, sub); err != nil { return nil, fmt.Errorf("waiting for the stored batches: %w", err) } // EOSE says the stored events have been sent, not that they have all been // read out of the subscription, so the queue is drained after it rather // than during it. var events []*nostr.Event for drained := true; drained; { select { case ev := <-sub.Events: if ev != nil { events = append(events, ev) } default: drained = false } } return c.runs(events, from, to) } // runs decodes the batches and returns them in ascending height order. func (c *Cache) runs(events []*nostr.Event, from, to uint32) ([]neutrino.Filters, error) { seen := make(map[string]bool, len(events)) runs := make([]neutrino.Filters, 0, len(events)) broken := 0 for _, ev := range events { key := nostr.Hex(ev.ID[:]) if seen[key] { continue } seen[key] = true batch, err := cfevents.Decode(ev) if err != nil { broken++ continue } if batch.Chain != c.cfg.Chain { continue } // A batch that does not touch the window is no use; a relay that // answered loosely should not cost the client anything. if batch.To() < from || batch.From > to { continue } runs = append(runs, neutrino.Filters{From: batch.From, Filters: batch.Filters}) } if broken > 0 { c.cfg.Logf("filtercache: %d of %d batches did not decode", broken, len(events)) } sort.SliceStable(runs, func(i, j int) bool { return runs[i].From < runs[j].From }) return runs, nil } // client returns a live connection to one relay, opening one if the last ended. func (c *Cache) client(url string) (*relay.Client, error) { c.mu.Lock() defer c.mu.Unlock() if existing, ok := c.clients[url]; ok { select { case <-existing.Done(): _ = existing.Close() delete(c.clients, url) default: return existing, nil } } transport, err := c.cfg.Dial(url) if err != nil { return nil, err } // One subscription per window, and a window can name up to the client's cap // in heights, so the queue has to hold at least that many events. Three // times the cap covers the case a range was published twice under different // batch boundaries, which makes two events match one height. The relay's // reader drops rather than blocks when a queue fills, and a dropped event // is a filter the client fetches from the peer instead, so the slack is // cheaper than being tight. var key [32]byte if _, err := rand.Read(key[:]); err != nil { return nil, err } client, err := relay.New(transport, key, relay.Options{ RelayURL: url, EventBuffer: neutrino.SourceMaxWindow * 3, }) if err != nil { _ = transport.Close() return nil, err } c.clients[url] = client return client, nil } // Close ends every connection. func (c *Cache) Close() { c.mu.Lock() defer c.mu.Unlock() for url, client := range c.clients { _ = client.Close() delete(c.clients, url) } }