headercache.go raw

   1  // Package headercache reads block headers from relays that cache them.
   2  //
   3  // It is the relay side of neutrino.HeaderSource: the client asks for a height window, this
   4  // asks the relays for the events that cover it, decodes them, and hands back the run it got.
   5  // Nothing it returns is trusted: neutrino checks every header's proof of work and its parent,
   6  // and the header event itself is refused by the decoder unless the bytes hash to the block
   7  // hash the event names. A relay can withhold a header, and a withheld header costs a fetch
   8  // from the tunnel; it cannot change one.
   9  //
  10  // A window with no answer is not an error. It is how a source says it holds nothing for the
  11  // range, and neutrino then asks the peer exactly as it would without a source.
  12  package headercache
  13  
  14  import (
  15  	"context"
  16  	"crypto/rand"
  17  	"errors"
  18  	"fmt"
  19  	"sort"
  20  	"strings"
  21  	"sync"
  22  	"time"
  23  
  24  	"git.smesh.lol/nostrino/pkg/btcwire"
  25  	"git.smesh.lol/nostrino/pkg/headerevents"
  26  	"git.smesh.lol/nostrino/pkg/nostr"
  27  	"git.smesh.lol/nostrino/pkg/relay"
  28  )
  29  
  30  // Config describes where the header events come from.
  31  type Config struct {
  32  	// Chain is the chain name the events are tagged with.
  33  	Chain string
  34  	// Relays are asked in order and the first that answers is used.
  35  	Relays []string
  36  	// Dial opens a relay transport. In a browser it is the page's WebSocket.
  37  	Dial func(string) (relay.Transport, error)
  38  	// Wait bounds one relay round trip: REQ, the stored events, EOSE.
  39  	Wait time.Duration
  40  	// Logf receives one line per answered window; nil discards them.
  41  	Logf func(string, ...any)
  42  }
  43  
  44  // Cache is a relay-backed header source. One per chain.
  45  type Cache struct {
  46  	cfg Config
  47  
  48  	mu      sync.Mutex
  49  	clients map[string]*relay.Client
  50  }
  51  
  52  // New validates the configuration. It does not connect.
  53  func New(cfg Config) (*Cache, error) {
  54  	if strings.TrimSpace(cfg.Chain) == "" {
  55  		return nil, errors.New("headercache: no chain")
  56  	}
  57  
  58  	if len(cfg.Relays) == 0 {
  59  		return nil, errors.New("headercache: no relay")
  60  	}
  61  
  62  	if cfg.Dial == nil {
  63  		return nil, errors.New("headercache: no transport")
  64  	}
  65  
  66  	if cfg.Wait <= 0 {
  67  		// A window is a few hundred small events, so the bound is the relay's answer and not
  68  		// the transfer: ten seconds is generous for a stored read and short enough that a
  69  		// silent relay falls through to the peer.
  70  		cfg.Wait = 10 * time.Second
  71  	}
  72  
  73  	if cfg.Logf == nil {
  74  		cfg.Logf = func(string, ...any) {}
  75  	}
  76  
  77  	return &Cache{cfg: cfg, clients: make(map[string]*relay.Client)}, nil
  78  }
  79  
  80  // Headers asks the relays for the header events covering [from,to].
  81  //
  82  // The answer is a contiguous run starting at from, or nothing: neutrino appends it to its own
  83  // chain, so a run with a hole in it would be rejected anyway and is not worth returning.
  84  func (c *Cache) Headers(ctx context.Context, from, to uint32) ([]btcwire.BlockHeader, error) {
  85  	if to < from {
  86  		return nil, fmt.Errorf("headercache: range %d..%d is reversed", from, to)
  87  	}
  88  
  89  	query := headerevents.Query(c.cfg.Chain, from, to)
  90  
  91  	var failures []string
  92  
  93  	for _, url := range c.cfg.Relays {
  94  		run, err := c.ask(ctx, url, query, from, to)
  95  
  96  		if err != nil {
  97  			failures = append(failures, url+": "+err.Error())
  98  
  99  			continue
 100  		}
 101  
 102  		if len(run) == 0 {
 103  			return nil, nil
 104  		}
 105  
 106  		c.cfg.Logf("headercache: %d..%d answered with %d header(s) from %s",
 107  			from, to, len(run), url)
 108  
 109  		return run, nil
 110  	}
 111  
 112  	if len(failures) > 0 {
 113  		return nil, errors.New(strings.Join(failures, "; "))
 114  	}
 115  
 116  	return nil, nil
 117  }
 118  
 119  // ask runs one REQ against one relay and returns the contiguous run it holds.
 120  func (c *Cache) ask(ctx context.Context, url string, query nostr.Filter, from, to uint32) ([]btcwire.BlockHeader, error) {
 121  	client, err := c.client(url)
 122  
 123  	if err != nil {
 124  		return nil, err
 125  	}
 126  
 127  	sub, err := client.Subscribe(query)
 128  
 129  	if err != nil {
 130  		return nil, err
 131  	}
 132  
 133  	defer sub.Close()
 134  
 135  	waitCtx, cancel := context.WithTimeout(ctx, c.cfg.Wait)
 136  	defer cancel()
 137  
 138  	if err := client.WaitEOSE(waitCtx, sub); err != nil {
 139  		return nil, fmt.Errorf("waiting for the stored headers: %w", err)
 140  	}
 141  
 142  	// EOSE says the stored events have been sent, not that they have been read out of the
 143  	// subscription, so the queue is drained after it rather than during it.
 144  	var events []*nostr.Event
 145  
 146  	for drained := true; drained; {
 147  		select {
 148  		case ev := <-sub.Events:
 149  			if ev != nil {
 150  				events = append(events, ev)
 151  			}
 152  		default:
 153  			drained = false
 154  		}
 155  	}
 156  
 157  	return c.run(events, from, to)
 158  }
 159  
 160  // run decodes the events and returns the contiguous run that starts at from.
 161  //
 162  // Two headers can exist at one height during a reorg, and the run keeps the first one seen:
 163  // which of them is right is the chain's question, and neutrino answers it by proof of work and
 164  // by asking the tunnel when the two disagree.
 165  func (c *Cache) run(events []*nostr.Event, from, to uint32) ([]btcwire.BlockHeader, error) {
 166  	seen := make(map[string]bool, len(events))
 167  	byHeight := make(map[uint32]btcwire.BlockHeader, len(events))
 168  	broken := 0
 169  
 170  	for _, ev := range events {
 171  		key := nostr.Hex(ev.ID[:])
 172  
 173  		if seen[key] {
 174  			continue
 175  		}
 176  
 177  		seen[key] = true
 178  
 179  		header, err := headerevents.Decode(ev)
 180  
 181  		if err != nil {
 182  			broken++
 183  
 184  			continue
 185  		}
 186  
 187  		if header.Chain != c.cfg.Chain {
 188  			continue
 189  		}
 190  
 191  		if header.Height < from || header.Height > to {
 192  			continue
 193  		}
 194  
 195  		if _, present := byHeight[header.Height]; present {
 196  			continue
 197  		}
 198  
 199  		byHeight[header.Height] = header.Raw
 200  	}
 201  
 202  	if broken > 0 {
 203  		c.cfg.Logf("headercache: %d of %d header events did not decode", broken, len(events))
 204  	}
 205  
 206  	heights := make([]uint32, 0, len(byHeight))
 207  
 208  	for height := range byHeight {
 209  		heights = append(heights, height)
 210  	}
 211  
 212  	sort.Slice(heights, func(i, j int) bool { return heights[i] < heights[j] })
 213  
 214  	run := make([]btcwire.BlockHeader, 0, len(heights))
 215  
 216  	for _, height := range heights {
 217  		if height != from+uint32(len(run)) {
 218  			// A hole: the events above it are not usable by a client that appends.
 219  			break
 220  		}
 221  
 222  		run = append(run, byHeight[height])
 223  	}
 224  
 225  	return run, nil
 226  }
 227  
 228  // client returns a live connection to one relay, opening one if the last ended.
 229  func (c *Cache) client(url string) (*relay.Client, error) {
 230  	c.mu.Lock()
 231  	defer c.mu.Unlock()
 232  
 233  	if existing, ok := c.clients[url]; ok {
 234  		select {
 235  		case <-existing.Done():
 236  			_ = existing.Close()
 237  			delete(c.clients, url)
 238  		default:
 239  			return existing, nil
 240  		}
 241  	}
 242  
 243  	transport, err := c.cfg.Dial(url)
 244  
 245  	if err != nil {
 246  		return nil, err
 247  	}
 248  
 249  	var key [32]byte
 250  
 251  	if _, err := rand.Read(key[:]); err != nil {
 252  		return nil, err
 253  	}
 254  
 255  	client, err := relay.New(transport, key, relay.Options{
 256  		RelayURL: url,
 257  		// One event per height, so the queue has to hold a window with slack for a height
 258  		// that was published twice.
 259  		EventBuffer: 1024,
 260  	})
 261  
 262  	if err != nil {
 263  		_ = transport.Close()
 264  
 265  		return nil, err
 266  	}
 267  
 268  	c.clients[url] = client
 269  
 270  	return client, nil
 271  }
 272  
 273  // Close ends every connection.
 274  func (c *Cache) Close() {
 275  	c.mu.Lock()
 276  	defer c.mu.Unlock()
 277  
 278  	for url, client := range c.clients {
 279  		_ = client.Close()
 280  
 281  		delete(c.clients, url)
 282  	}
 283  }
 284