// Package headercache reads block headers from relays that cache them. // // It is the relay side of neutrino.HeaderSource: the client asks for a height window, this // asks the relays for the events that cover it, decodes them, and hands back the run it got. // Nothing it returns is trusted: neutrino checks every header's proof of work and its parent, // and the header event itself is refused by the decoder unless the bytes hash to the block // hash the event names. A relay can withhold a header, and a withheld header costs a fetch // from the tunnel; it cannot change one. // // A window with no answer is not an error. It is how a source says it holds nothing for the // range, and neutrino then asks the peer exactly as it would without a source. package headercache import ( "context" "crypto/rand" "errors" "fmt" "sort" "strings" "sync" "time" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/headerevents" "git.smesh.lol/nostrino/pkg/nostr" "git.smesh.lol/nostrino/pkg/relay" ) // Config describes where the header events come from. type Config struct { // Chain is the chain name the events 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) } // Cache is a relay-backed header source. One per chain. type Cache struct { cfg Config mu sync.Mutex clients map[string]*relay.Client } // New validates the configuration. It does not connect. func New(cfg Config) (*Cache, error) { if strings.TrimSpace(cfg.Chain) == "" { return nil, errors.New("headercache: no chain") } if len(cfg.Relays) == 0 { return nil, errors.New("headercache: no relay") } if cfg.Dial == nil { return nil, errors.New("headercache: no transport") } if cfg.Wait <= 0 { // A window is a few hundred small events, so the bound is the relay's answer and not // the transfer: ten seconds is generous for a stored read and short enough that a // silent relay falls through to the peer. cfg.Wait = 10 * time.Second } if cfg.Logf == nil { cfg.Logf = func(string, ...any) {} } return &Cache{cfg: cfg, clients: make(map[string]*relay.Client)}, nil } // Headers asks the relays for the header events covering [from,to]. // // The answer is a contiguous run starting at from, or nothing: neutrino appends it to its own // chain, so a run with a hole in it would be rejected anyway and is not worth returning. func (c *Cache) Headers(ctx context.Context, from, to uint32) ([]btcwire.BlockHeader, error) { if to < from { return nil, fmt.Errorf("headercache: range %d..%d is reversed", from, to) } query := headerevents.Query(c.cfg.Chain, from, to) var failures []string for _, url := range c.cfg.Relays { run, err := c.ask(ctx, url, query, from, to) if err != nil { failures = append(failures, url+": "+err.Error()) continue } if len(run) == 0 { return nil, nil } c.cfg.Logf("headercache: %d..%d answered with %d header(s) from %s", from, to, len(run), url) return run, nil } if len(failures) > 0 { return nil, errors.New(strings.Join(failures, "; ")) } return nil, nil } // ask runs one REQ against one relay and returns the contiguous run it holds. func (c *Cache) ask(ctx context.Context, url string, query nostr.Filter, from, to uint32) ([]btcwire.BlockHeader, 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 headers: %w", err) } // EOSE says the stored events have been sent, not that they have 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.run(events, from, to) } // run decodes the events and returns the contiguous run that starts at from. // // Two headers can exist at one height during a reorg, and the run keeps the first one seen: // which of them is right is the chain's question, and neutrino answers it by proof of work and // by asking the tunnel when the two disagree. func (c *Cache) run(events []*nostr.Event, from, to uint32) ([]btcwire.BlockHeader, error) { seen := make(map[string]bool, len(events)) byHeight := make(map[uint32]btcwire.BlockHeader, len(events)) broken := 0 for _, ev := range events { key := nostr.Hex(ev.ID[:]) if seen[key] { continue } seen[key] = true header, err := headerevents.Decode(ev) if err != nil { broken++ continue } if header.Chain != c.cfg.Chain { continue } if header.Height < from || header.Height > to { continue } if _, present := byHeight[header.Height]; present { continue } byHeight[header.Height] = header.Raw } if broken > 0 { c.cfg.Logf("headercache: %d of %d header events did not decode", broken, len(events)) } heights := make([]uint32, 0, len(byHeight)) for height := range byHeight { heights = append(heights, height) } sort.Slice(heights, func(i, j int) bool { return heights[i] < heights[j] }) run := make([]btcwire.BlockHeader, 0, len(heights)) for _, height := range heights { if height != from+uint32(len(run)) { // A hole: the events above it are not usable by a client that appends. break } run = append(run, byHeight[height]) } return run, 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 } var key [32]byte if _, err := rand.Read(key[:]); err != nil { return nil, err } client, err := relay.New(transport, key, relay.Options{ RelayURL: url, // One event per height, so the queue has to hold a window with slack for a height // that was published twice. EventBuffer: 1024, }) 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) } }