filtercache.go raw

   1  // Package filtercache reads compact filters from relays that cache them.
   2  //
   3  // It is the relay side of neutrino.FilterSource: the client asks for a range,
   4  // this asks the relays for the batches that cover it, decodes them, and hands
   5  // back the runs it got. Nothing it returns is trusted: neutrino verifies every
   6  // filter against the filter hash its own header chain commits to, so the relay's
   7  // position is the gateway's — it can deny service, not forge it.
   8  //
   9  // A cache miss is not an error. It is the normal answer for a range the relays
  10  // do not cover, and it falls through to the peer.
  11  package filtercache
  12  
  13  import (
  14  	"context"
  15  	"crypto/rand"
  16  	"errors"
  17  	"fmt"
  18  	"sort"
  19  	"strings"
  20  	"sync"
  21  	"time"
  22  
  23  	"git.smesh.lol/nostrino/pkg/cfevents"
  24  	"git.smesh.lol/nostrino/pkg/neutrino"
  25  	"git.smesh.lol/nostrino/pkg/nostr"
  26  	"git.smesh.lol/nostrino/pkg/relay"
  27  )
  28  
  29  // Config describes where the batches come from.
  30  type Config struct {
  31  	// Chain is the chain name the batches are tagged with.
  32  	Chain string
  33  	// Relays are asked in order and the first that answers is used.
  34  	Relays []string
  35  	// Dial opens a relay transport. In a browser it is the page's WebSocket.
  36  	Dial func(string) (relay.Transport, error)
  37  	// Wait bounds one relay round trip: REQ, the stored events, EOSE.
  38  	Wait time.Duration
  39  	// Logf receives one line per answered window; nil discards them.
  40  	Logf func(string, ...any)
  41  }
  42  
  43  // missReportEvery is how many consecutive empty windows pass between log lines.
  44  //
  45  // An empty window is a miss, which is normal: a cache starts where its sidecar
  46  // started and a wallet may scan below that. Giving up after a few misses would
  47  // be worse than the cost it saves, because the misses come first and the
  48  // coverage comes after: a wallet rescanning from an old swap height would pass
  49  // three uncovered windows and then never ask again, exactly where the cache
  50  // could have served it. One request per hundred blocks is a hundredth of what
  51  // the peer route costs, so asking every time is the cheap choice.
  52  const missReportEvery = 20
  53  
  54  // Cache is a relay-backed filter source. One per chain.
  55  type Cache struct {
  56  	cfg Config
  57  
  58  	mu      sync.Mutex
  59  	clients map[string]*relay.Client
  60  	// empty counts consecutive windows that came back with nothing.
  61  	empty int
  62  }
  63  
  64  // New validates the configuration. It does not connect.
  65  func New(cfg Config) (*Cache, error) {
  66  	if strings.TrimSpace(cfg.Chain) == "" {
  67  		return nil, errors.New("filtercache: no chain")
  68  	}
  69  
  70  	if len(cfg.Relays) == 0 {
  71  		return nil, errors.New("filtercache: no relay")
  72  	}
  73  
  74  	if cfg.Dial == nil {
  75  		return nil, errors.New("filtercache: no transport")
  76  	}
  77  
  78  	if cfg.Wait <= 0 {
  79  		// The wait covers one whole answer: the relay sends every stored
  80  		// batch and then EOSE, so the bound is the transfer of up to a hundred
  81  		// filters, not a round trip. At mainnet sizes that is nearly two
  82  		// megabytes, and a five second bound would abandon the window on any
  83  		// link slower than a few megabits, which would mean the cache and the
  84  		// peer both doing the work.
  85  		cfg.Wait = 30 * time.Second
  86  	}
  87  
  88  	if cfg.Logf == nil {
  89  		cfg.Logf = func(string, ...any) {}
  90  	}
  91  
  92  	return &Cache{cfg: cfg, clients: make(map[string]*relay.Client)}, nil
  93  }
  94  
  95  // Filters asks the relays for the batches covering [from,to].
  96  //
  97  // The result is at most one window of work: neutrino bounds the range it asks
  98  // for, so this never accumulates a scan.
  99  func (c *Cache) Filters(ctx context.Context, from, to uint32) ([]neutrino.Filters, error) {
 100  	if to < from {
 101  		return nil, fmt.Errorf("filtercache: range %d..%d is reversed", from, to)
 102  	}
 103  
 104  	query := cfevents.Query(c.cfg.Chain, from, to)
 105  
 106  	var failures []string
 107  
 108  	for _, url := range c.cfg.Relays {
 109  		runs, err := c.ask(ctx, url, query, from, to)
 110  
 111  		if err != nil {
 112  			failures = append(failures, url+": "+err.Error())
 113  
 114  			continue
 115  		}
 116  
 117  		c.report(from, to, runs)
 118  
 119  		return runs, nil
 120  	}
 121  
 122  	if len(failures) > 0 {
 123  		return nil, errors.New(strings.Join(failures, "; "))
 124  	}
 125  
 126  	return nil, nil
 127  }
 128  
 129  // report logs one answered window and keeps the miss count, so a scan served
 130  // from the cache looks like one and a scan that is not says why.
 131  //
 132  // Exactly one line per window, because one window is one request: a caller that
 133  // counts these lines is counting what went over the wire.
 134  func (c *Cache) report(from, to uint32, runs []neutrino.Filters) {
 135  	if len(runs) == 0 {
 136  		c.mu.Lock()
 137  		c.empty++
 138  		misses := c.empty
 139  		c.mu.Unlock()
 140  
 141  		if misses == 1 || misses%missReportEvery == 0 {
 142  			c.cfg.Logf("filtercache: no batch for %d..%d (%d in a row)", from, to, misses)
 143  		}
 144  
 145  		return
 146  	}
 147  
 148  	c.mu.Lock()
 149  	c.empty = 0
 150  	c.mu.Unlock()
 151  
 152  	filters := 0
 153  
 154  	for _, run := range runs {
 155  		filters += len(run.Filters)
 156  	}
 157  
 158  	c.cfg.Logf("filtercache: %d batches holding %d filters for %d..%d",
 159  		len(runs), filters, from, to)
 160  }
 161  
 162  // ask runs one REQ against one relay and returns the batches it holds.
 163  func (c *Cache) ask(ctx context.Context, url string, query nostr.Filter, from, to uint32) ([]neutrino.Filters, error) {
 164  	client, err := c.client(url)
 165  
 166  	if err != nil {
 167  		return nil, err
 168  	}
 169  
 170  	sub, err := client.Subscribe(query)
 171  
 172  	if err != nil {
 173  		return nil, err
 174  	}
 175  
 176  	defer sub.Close()
 177  
 178  	waitCtx, cancel := context.WithTimeout(ctx, c.cfg.Wait)
 179  	defer cancel()
 180  
 181  	if err := client.WaitEOSE(waitCtx, sub); err != nil {
 182  		return nil, fmt.Errorf("waiting for the stored batches: %w", err)
 183  	}
 184  
 185  	// EOSE says the stored events have been sent, not that they have all been
 186  	// read out of the subscription, so the queue is drained after it rather
 187  	// than during it.
 188  	var events []*nostr.Event
 189  
 190  	for drained := true; drained; {
 191  		select {
 192  		case ev := <-sub.Events:
 193  			if ev != nil {
 194  				events = append(events, ev)
 195  			}
 196  		default:
 197  			drained = false
 198  		}
 199  	}
 200  
 201  	return c.runs(events, from, to)
 202  }
 203  
 204  // runs decodes the batches and returns them in ascending height order.
 205  func (c *Cache) runs(events []*nostr.Event, from, to uint32) ([]neutrino.Filters, error) {
 206  	seen := make(map[string]bool, len(events))
 207  	runs := make([]neutrino.Filters, 0, len(events))
 208  	broken := 0
 209  
 210  	for _, ev := range events {
 211  		key := nostr.Hex(ev.ID[:])
 212  
 213  		if seen[key] {
 214  			continue
 215  		}
 216  
 217  		seen[key] = true
 218  
 219  		batch, err := cfevents.Decode(ev)
 220  
 221  		if err != nil {
 222  			broken++
 223  
 224  			continue
 225  		}
 226  
 227  		if batch.Chain != c.cfg.Chain {
 228  			continue
 229  		}
 230  
 231  		// A batch that does not touch the window is no use; a relay that
 232  		// answered loosely should not cost the client anything.
 233  		if batch.To() < from || batch.From > to {
 234  			continue
 235  		}
 236  
 237  		runs = append(runs, neutrino.Filters{From: batch.From, Filters: batch.Filters})
 238  	}
 239  
 240  	if broken > 0 {
 241  		c.cfg.Logf("filtercache: %d of %d batches did not decode", broken, len(events))
 242  	}
 243  
 244  	sort.SliceStable(runs, func(i, j int) bool { return runs[i].From < runs[j].From })
 245  
 246  	return runs, nil
 247  }
 248  
 249  // client returns a live connection to one relay, opening one if the last ended.
 250  func (c *Cache) client(url string) (*relay.Client, error) {
 251  	c.mu.Lock()
 252  	defer c.mu.Unlock()
 253  
 254  	if existing, ok := c.clients[url]; ok {
 255  		select {
 256  		case <-existing.Done():
 257  			_ = existing.Close()
 258  			delete(c.clients, url)
 259  		default:
 260  			return existing, nil
 261  		}
 262  	}
 263  
 264  	transport, err := c.cfg.Dial(url)
 265  
 266  	if err != nil {
 267  		return nil, err
 268  	}
 269  
 270  	// One subscription per window, and a window can name up to the client's cap
 271  	// in heights, so the queue has to hold at least that many events. Three
 272  	// times the cap covers the case a range was published twice under different
 273  	// batch boundaries, which makes two events match one height. The relay's
 274  	// reader drops rather than blocks when a queue fills, and a dropped event
 275  	// is a filter the client fetches from the peer instead, so the slack is
 276  	// cheaper than being tight.
 277  	var key [32]byte
 278  
 279  	if _, err := rand.Read(key[:]); err != nil {
 280  		return nil, err
 281  	}
 282  
 283  	client, err := relay.New(transport, key, relay.Options{
 284  		RelayURL:    url,
 285  		EventBuffer: neutrino.SourceMaxWindow * 3,
 286  	})
 287  
 288  	if err != nil {
 289  		_ = transport.Close()
 290  
 291  		return nil, err
 292  	}
 293  
 294  	c.clients[url] = client
 295  
 296  	return client, nil
 297  }
 298  
 299  // Close ends every connection.
 300  func (c *Cache) Close() {
 301  	c.mu.Lock()
 302  	defer c.mu.Unlock()
 303  
 304  	for url, client := range c.clients {
 305  		_ = client.Close()
 306  		delete(c.clients, url)
 307  	}
 308  }
 309