main.go raw

   1  // Command nostrino-filtercache publishes a chain's compact filters to a relay.
   2  //
   3  // A wallet that follows a chain through BIP157 needs one filter per block it
   4  // scans, and a node serves them one getcfilters round trip at a time. That is
   5  // the cost this program removes: it reads the filters from a node it trusts,
   6  // batches them into events, and publishes them once so any number of wallets
   7  // can read them from the relay instead. The wallet still verifies every filter
   8  // against the filter hash its own header chain commits to, so the relay gains
   9  // no authority by holding them.
  10  //
  11  // The filter cache is built from a node and never from another cache: one bad
  12  // batch republished by a second cache would spread to every client that trusts
  13  // relays.
  14  //
  15  // Progress is a watermark in the data directory. Batches are cut by byte budget
  16  // from the watermark, so a restart cuts them in the same places: the same run
  17  // produces the same events, and re-publishing one costs a "duplicate" answer
  18  // rather than a second copy in the relay.
  19  package main
  20  
  21  import (
  22  	"context"
  23  	"crypto/rand"
  24  	"encoding/json"
  25  	"errors"
  26  	"flag"
  27  	"fmt"
  28  	"net"
  29  	"net/http"
  30  	"net/url"
  31  	"os"
  32  	"os/signal"
  33  	"path/filepath"
  34  	"strings"
  35  	"syscall"
  36  	"time"
  37  
  38  	"git.smesh.lol/nostrino/pkg/blockcache"
  39  	"git.smesh.lol/nostrino/pkg/btcwire"
  40  	"git.smesh.lol/nostrino/pkg/cfevents"
  41  	"git.smesh.lol/nostrino/pkg/chain"
  42  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  43  	"git.smesh.lol/nostrino/pkg/crypto/secp256k1"
  44  	"git.smesh.lol/nostrino/pkg/headerevents"
  45  	"git.smesh.lol/nostrino/pkg/nostr"
  46  	"git.smesh.lol/nostrino/pkg/relay"
  47  )
  48  
  49  func main() {
  50  	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
  51  	defer stop()
  52  	if err := run(ctx, os.Args[1:]); err != nil {
  53  		fmt.Fprintln(os.Stderr, "nostrino-filtercache:", err)
  54  		os.Exit(1)
  55  	}
  56  }
  57  
  58  // config is what the flags describe.
  59  type config struct {
  60  	nodeURL string
  61  	cookie  string
  62  	// peer is a P2P address to follow instead of an RPC node, for a sidecar that has no node of
  63  	// its own beside the gateway.
  64  	peer string
  65  	// genesisAnchor starts the header chain at genesis rather than the profile's checkpoint, for
  66  	// a peer that answers nothing to a checkpoint locator.
  67  	genesisAnchor bool
  68  	// noFilters turns off the filter batches. A peer that does not serve BIP157 is still a peer
  69  	// for headers and blocks, and a sidecar that dies on a filter it cannot get is a sidecar that
  70  	// publishes nothing else.
  71  	noFilters bool
  72  	// noHeaders turns off the header events, for a peer that will not serve a header chain from
  73  	// the anchor this sidecar has.
  74  	noHeaders bool
  75  	chain     *chain.Profile
  76  	relays    []string
  77  	data      string
  78  	from      uint32
  79  	fromSet   bool
  80  	poll      time.Duration
  81  	once      bool
  82  	headers   bool
  83  	// tag is the chain name the events carry and the block service answers to. The profile
  84  	// is the network's parameters; the tag is which of the application's chains the data is
  85  	// for. Two regtest nodes are one profile and two chains, and a client looking for blake
  86  	// would otherwise read btc's headers.
  87  	tag string
  88  	// The block service: where it listens, where its cache lives and how big it may grow.
  89  	blockListen   string
  90  	blockDir      string
  91  	blockBytes    int64
  92  	blockPrefetch int
  93  	status        bool
  94  	pubkey        bool
  95  	keyFile       string
  96  	attempts      int
  97  }
  98  
  99  // chainNode is the node side of the cache: the four reads it makes, and nothing
 100  // else. It is a seam, not scaffolding: it keeps the program's dependence on the
 101  // node enumerable, and it lets the publish loop be driven by a fixture.
 102  // chainNode is where one chain's data is read from.
 103  //
 104  // It is keyed by height because that is what the publisher walks and what an accumulator of
 105  // headers has: an interface keyed by hash would make every implementation carry a height to
 106  // hash lookup for the one caller that wants a block by name.
 107  type chainNode interface {
 108  	tip(context.Context) (uint32, error)
 109  	// header returns one block header at a height, which is what the header events carry.
 110  	header(context.Context, uint32) (btcwire.BlockHeader, error)
 111  	blockTime(context.Context, uint32) (int64, error)
 112  	filter(context.Context, uint32) ([]byte, chainhash.Hash, error)
 113  	block(context.Context, uint32) ([]byte, error)
 114  	blockByHash(context.Context, chainhash.Hash) ([]byte, error)
 115  }
 116  
 117  // eventSink is where batches go.
 118  type eventSink interface {
 119  	publish(context.Context, *nostr.Event) error
 120  }
 121  
 122  var (
 123  	_ chainNode = (*node)(nil)
 124  	_ eventSink = (*publisher)(nil)
 125  )
 126  
 127  func run(ctx context.Context, args []string) error {
 128  	cfg, err := parseFlags(args)
 129  	if err != nil {
 130  		return err
 131  	}
 132  
 133  	statePath := filepath.Join(cfg.data, "state.json")
 134  	prev, err := loadState(statePath)
 135  	if err != nil {
 136  		return err
 137  	}
 138  	if prev != nil && prev.Chain != cfg.tag {
 139  		return fmt.Errorf("%s holds progress for chain %q, not %q: one data directory per chain",
 140  			statePath, prev.Chain, cfg.tag)
 141  	}
 142  
 143  	if cfg.status {
 144  		return printStatus(cfg, prev)
 145  	}
 146  
 147  	//
 148  	// The identity is a fact an operator has to copy into a relay policy, so it
 149  	// can be printed without starting a publish loop: one flag, one line on
 150  	// stdout, and no node or relay touched. It creates the key when the file is
 151  	// absent, which is the same thing the loop would do.
 152  	//
 153  	if cfg.pubkey {
 154  		_, pub, fresh, err := loadKey(cfg.keyFile)
 155  		if err != nil {
 156  			return err
 157  		}
 158  		if fresh {
 159  			fmt.Fprintf(os.Stderr, "new identity written to %s\n", cfg.keyFile)
 160  		}
 161  		fmt.Println(nostr.Hex(pub[:]))
 162  		return nil
 163  	}
 164  
 165  	if err := os.MkdirAll(cfg.data, 0o755); err != nil {
 166  		return err
 167  	}
 168  
 169  	var (
 170  		source chainNode
 171  		closer func()
 172  	)
 173  
 174  	switch {
 175  	case strings.TrimSpace(cfg.peer) != "":
 176  		profile := cfg.chain
 177  
 178  		if cfg.genesisAnchor {
 179  			fromGenesis := *profile
 180  			fromGenesis.Checkpoint = nil
 181  			profile = &fromGenesis
 182  		}
 183  
 184  		followed, err := openP2PNode(ctx, profile, filepath.Join(cfg.data, "peerstore"), cfg.peer, logf)
 185  
 186  		if err != nil {
 187  			return err
 188  		}
 189  
 190  		source, closer = followed, followed.close
 191  
 192  		logf("following the peer %s for %s", cfg.peer, cfg.tag)
 193  
 194  	case strings.TrimSpace(cfg.nodeURL) != "":
 195  		rpcNode, err := newNode(cfg.nodeURL, cfg.cookie)
 196  
 197  		if err != nil {
 198  			return err
 199  		}
 200  
 201  		source = rpcNode
 202  
 203  	default:
 204  		return errors.New("either -node (JSON-RPC) or -peer (P2P) is required")
 205  	}
 206  
 207  	if closer != nil {
 208  		defer closer()
 209  	}
 210  
 211  	// The chain tag is what a wallet subscribes to, so the node behind it has to
 212  	// be the chain the profile names. Genesis is the cheapest proof of that, and
 213  	// pointing a mainnet profile at a regtest node is a mistake worth catching
 214  	// before it publishes nineteen thousand blocks of the wrong filters.
 215  	if rpcNode, ok := source.(*node); ok {
 216  		if err := checkGenesis(ctx, rpcNode, cfg.chain); err != nil {
 217  			return err
 218  		}
 219  	}
 220  
 221  	if prev == nil && !cfg.fromSet {
 222  		tip, err := source.tip(ctx)
 223  		if err != nil {
 224  			return err
 225  		}
 226  
 227  		//
 228  		// A store whose only header is its anchor has nothing to publish at the tip: the anchor
 229  		// is a height this sidecar has no header for, so the first publishable height is the one
 230  		// above it. That is the normal state of a chain whose peer is at the checkpoint, and it is
 231  		// a wait, not a failure.
 232  		//
 233  		if _, err := source.header(ctx, tip); err != nil {
 234  			tip++
 235  		}
 236  
 237  		cfg.from = tip
 238  
 239  		logf("a fresh cache for %s starts at %d; -from backfills", cfg.tag, tip)
 240  	}
 241  
 242  	key, pub, fresh, err := loadKey(cfg.keyFile)
 243  	if err != nil {
 244  		return err
 245  	}
 246  	if fresh {
 247  		logf("new identity written to %s", cfg.keyFile)
 248  	}
 249  	logf("chain=%s (tag %s) relays=%s pubkey=%s", cfg.chain.Name, cfg.tag, strings.Join(cfg.relays, ","), nostr.Hex(pub[:]))
 250  
 251  	send := newPublisher(cfg.relays, key)
 252  	defer send.close()
 253  
 254  	st := &state{
 255  		Chain: cfg.tag, PublishedTo: int64(cfg.from) - 1,
 256  		HeadersTo: int64(cfg.from) - 1, Start: cfg.from,
 257  	}
 258  	if prev != nil {
 259  		st = prev
 260  		if st.PublishedTo+1 < int64(cfg.from) {
 261  			// The flag moved forward, so the gap below it is now somebody
 262  			// else's problem; say so rather than pretend coverage is complete.
 263  			logf("progress says %d, so the range below %d will not be published", st.PublishedTo, cfg.from)
 264  			st.PublishedTo = int64(cfg.from) - 1
 265  			st.HeadersTo = int64(cfg.from) - 1
 266  		}
 267  	}
 268  
 269  	blocks, err := startBlockService(ctx, cfg, source)
 270  	if err != nil {
 271  		return err
 272  	}
 273  	if blocks != nil {
 274  		defer blocks.cache.Close()
 275  	}
 276  
 277  	return follow(ctx, cfg, source, send, st, statePath, blocks)
 278  }
 279  
 280  // startBlockService brings the HTTP block service up when one was asked for.
 281  //
 282  // It returns nil when no address was configured, which is the default: a sidecar that only
 283  // publishes events needs no listener, and an operator who has not opened one has not thought
 284  // about who can reach it.
 285  func startBlockService(ctx context.Context, cfg *config, node blockReader) (*blockService, error) {
 286  	if cfg.blockListen == "" {
 287  		return nil, nil
 288  	}
 289  
 290  	dir := cfg.blockDir
 291  	if dir == "" {
 292  		dir = filepath.Join(cfg.data, "blocks")
 293  	}
 294  
 295  	cache, err := blockcache.Open(blockcache.Config{Dir: dir, MaxBytes: cfg.blockBytes, Logf: logf})
 296  	if err != nil {
 297  		return nil, err
 298  	}
 299  
 300  	// The route resolves the name it is given to a profile and compares that
 301  	// profile's name, so the service is told the profile, not the tag. A forked
 302  	// chain's tag is the application's name: blake is the xbt profile, and a
 303  	// service told "blake" rejected both spellings of its own chain.
 304  	blocks := newBlockService(cfg.chain.Name, node, cache, logf)
 305  
 306  	listener, err := net.Listen("tcp", cfg.blockListen)
 307  	if err != nil {
 308  		_ = cache.Close()
 309  
 310  		return nil, err
 311  	}
 312  
 313  	server := &http.Server{Handler: blocks.handler(), ReadHeaderTimeout: 15 * time.Second}
 314  
 315  	go func() {
 316  		if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
 317  			logf("block service stopped: %v", err)
 318  		}
 319  	}()
 320  
 321  	go func() {
 322  		<-ctx.Done()
 323  		_ = server.Close()
 324  	}()
 325  
 326  	held, bytes := cache.Len()
 327  	logf("block service on http://%s/block/%s/<hash>, cache %s holding %d block(s) in %s",
 328  		listener.Addr(), cfg.tag, size(int(bytes)), held, dir)
 329  
 330  	return blocks, nil
 331  }
 332  
 333  // follow is the publishing loop: backfill to the node tip, then follow it.
 334  func follow(
 335  	ctx context.Context, cfg *config, node chainNode, pub eventSink,
 336  	st *state, statePath string, blocks *blockService,
 337  ) error {
 338  	// A fixture or a caller that set only the profile publishes under its name, which is what
 339  	// -tag defaults to.
 340  	if cfg.tag == "" {
 341  		cfg.tag = cfg.chain.Name
 342  	}
 343  
 344  	for {
 345  		tip, err := node.tip(ctx)
 346  		if err != nil {
 347  			return err
 348  		}
 349  		st.Tip = int64(tip)
 350  
 351  		//
 352  		// Headers first, then the filters. A client chains headers from a checkpoint it
 353  		// trusts and derives the filter-header chain from the filter hashes, so a filter
 354  		// batch is only usable once its headers are there: publishing them in that order
 355  		// means the newest block is scannable as soon as the second event lands.
 356  		//
 357  		if cfg.headers {
 358  			for st.HeadersTo < int64(tip) {
 359  				height := uint32(st.HeadersTo + 1)
 360  
 361  				header, err := node.header(ctx, height)
 362  				if err != nil {
 363  					st.LastError = err.Error()
 364  					_ = saveState(statePath, st)
 365  
 366  					return err
 367  				}
 368  
 369  				ev, err := headerevents.Encode(cfg.tag, height, &header)
 370  				if err != nil {
 371  					st.LastError = err.Error()
 372  					_ = saveState(statePath, st)
 373  
 374  					return fmt.Errorf("encode header %d: %w", height, err)
 375  				}
 376  
 377  				if err := publishWithRetry(ctx, pub, &ev, cfg.attempts); err != nil {
 378  					st.LastError = err.Error()
 379  					_ = saveState(statePath, st)
 380  
 381  					return fmt.Errorf("publish header %d: %w", height, err)
 382  				}
 383  
 384  				st.HeadersTo = int64(height)
 385  				st.Headers++
 386  
 387  				// The block service holds the newest blocks before anyone asks: the first
 388  				// client to need a new block would otherwise pay the node read, and the point
 389  				// of the cache is that nobody has to pay it twice.
 390  				if blocks != nil && height+uint32(cfg.blockPrefetch) >= tip {
 391  					blocks.prefetch(ctx, height, header.BlockHash())
 392  				}
 393  
 394  				// A backfill saves every hundred heights and the tip saves each time: the
 395  				// watermark only has to be close enough that a crash republishes a run of
 396  				// duplicates, which a relay answers as success.
 397  				if height%100 == 0 || height == tip {
 398  					if err := saveState(statePath, st); err != nil {
 399  						return err
 400  					}
 401  				}
 402  			}
 403  
 404  			logf("headers published to %d", st.HeadersTo)
 405  		}
 406  
 407  		for !cfg.noFilters && st.PublishedTo < int64(tip) {
 408  			from := uint32(st.PublishedTo + 1)
 409  			started := time.Now()
 410  
 411  			batch, err := build(ctx, node, cfg.tag, from, tip)
 412  			if err != nil {
 413  				st.LastError = err.Error()
 414  				_ = saveState(statePath, st)
 415  				return err
 416  			}
 417  
 418  			ev, err := batch.Encode()
 419  			if err != nil {
 420  				st.LastError = err.Error()
 421  				_ = saveState(statePath, st)
 422  				return fmt.Errorf("encode %d..%d: %w", from, batch.To(), err)
 423  			}
 424  
 425  			if err := publishWithRetry(ctx, pub, &ev, cfg.attempts); err != nil {
 426  				st.LastError = err.Error()
 427  				_ = saveState(statePath, st)
 428  				return fmt.Errorf("publish %d..%d: %w", from, batch.To(), err)
 429  			}
 430  
 431  			st.PublishedTo = int64(batch.To())
 432  			st.Batches++
 433  			st.LastError = ""
 434  			if err := saveState(statePath, st); err != nil {
 435  				return err
 436  			}
 437  
 438  			logf("published %s %d..%d (%d filters, %s) id=%s in %s",
 439  				cfg.tag, batch.From, batch.To(), batch.Len(),
 440  				size(len(ev.Content)), nostr.Hex(ev.ID[:]), time.Since(started).Round(time.Millisecond))
 441  		}
 442  
 443  		if cfg.once {
 444  			logf("at the node tip %d, stopping as asked", tip)
 445  			return nil
 446  		}
 447  
 448  		select {
 449  		case <-ctx.Done():
 450  			return nil
 451  		case <-time.After(cfg.poll):
 452  		}
 453  	}
 454  }
 455  
 456  // build fills one batch from from, adding filters until the next would not fit.
 457  func build(ctx context.Context, node chainNode, chainName string, from, tip uint32) (*cfevents.Batch, error) {
 458  	batch := &cfevents.Batch{Chain: chainName, From: from}
 459  
 460  	var last uint32
 461  	var count uint32
 462  	for height := from; height <= tip; height++ {
 463  		filter, filterHash, err := node.filter(ctx, height)
 464  		if err != nil {
 465  			return nil, err
 466  		}
 467  		err = batch.Add(filterHash, filter)
 468  		if errors.Is(err, cfevents.ErrFull) {
 469  			break
 470  		}
 471  		if err != nil {
 472  			return nil, fmt.Errorf("height %d: %w", height, err)
 473  		}
 474  		last = height
 475  		count++
 476  	}
 477  
 478  	if count == 0 {
 479  		return nil, fmt.Errorf("no filter at %d fits in one event (a filter over %d bytes?)",
 480  			from, cfevents.BodySize)
 481  	}
 482  
 483  	// created_at is the last block's time, so the event id depends on the chain
 484  	// and not on when this program ran.
 485  	at, err := node.blockTime(ctx, last)
 486  	if err != nil {
 487  		return nil, err
 488  	}
 489  	batch.At = at
 490  
 491  	return batch, nil
 492  }
 493  
 494  // publishTimeout bounds one publish attempt: dial, auth, and the relay's OK.
 495  const publishTimeout = 90 * time.Second
 496  
 497  // publishWithRetry sends one event, retrying while the failure could be
 498  // temporary. The event id is fixed, so a retry after a rejection that did get
 499  // stored costs a "duplicate" answer.
 500  func publishWithRetry(ctx context.Context, pub eventSink, ev *nostr.Event, attempts int) error {
 501  	backoff := time.Second
 502  	for attempt := 1; ; attempt++ {
 503  		// One attempt is bounded. A relay that accepts the connection and then
 504  		// answers nothing must not own the process: the dial, the auth
 505  		// handshake and the OK all live inside this deadline.
 506  		attemptCtx, cancel := context.WithTimeout(ctx, publishTimeout)
 507  		err := pub.publish(attemptCtx, ev)
 508  		cancel()
 509  
 510  		if err == nil {
 511  			return nil
 512  		}
 513  
 514  		// A refusal the relay will repeat is not worth eight rounds of
 515  		// backoff: the operator needs the relay's own words now, with the
 516  		// watermark still where it was.
 517  		var rejection *relay.Rejection
 518  		if errors.As(err, &rejection) {
 519  			// A deterministic producer republishes the same event after a crash, and the
 520  			// relay answering "duplicate" means the event is already there, which is all
 521  			// this loop wanted.
 522  			if rejection.Duplicate() {
 523  				return nil
 524  			}
 525  
 526  			if !rejection.Retryable() {
 527  				return fmt.Errorf("the relay refused permanently: %w", err)
 528  			}
 529  		}
 530  
 531  		if attempt >= attempts {
 532  			return fmt.Errorf("%w (after %d attempts)", err, attempt)
 533  		}
 534  		logf("publish failed, retrying in %s: %v", backoff, err)
 535  		select {
 536  		case <-ctx.Done():
 537  			return ctx.Err()
 538  		case <-time.After(backoff):
 539  		}
 540  		if backoff < 30*time.Second {
 541  			backoff *= 2
 542  		}
 543  	}
 544  }
 545  
 546  // checkGenesis refuses a node that is not the chain the profile names.
 547  func checkGenesis(ctx context.Context, node *node, profile *chain.Profile) error {
 548  	hash, err := node.blockHash(ctx, 0)
 549  	if err != nil {
 550  		return err
 551  	}
 552  	if hash != profile.GenesisHash {
 553  		return fmt.Errorf("the node's genesis is %s, but %s has %s: wrong node for this chain",
 554  			hash, profile.Name, profile.GenesisHash)
 555  	}
 556  	return nil
 557  }
 558  
 559  // state is the data directory's record of what has been published.
 560  type state struct {
 561  	Chain       string `json:"chain"`
 562  	Start       uint32 `json:"start"`
 563  	PublishedTo int64  `json:"published_to"`
 564  	// HeadersTo is the highest height whose header event is published. It is separate from
 565  	// PublishedTo because the two events carry different things and a run can be interrupted
 566  	// between them.
 567  	HeadersTo int64  `json:"headers_to"`
 568  	Tip       int64  `json:"node_tip"`
 569  	Batches   int    `json:"batches"`
 570  	Headers   int    `json:"headers,omitempty"`
 571  	Updated   string `json:"updated"`
 572  	LastError string `json:"last_error,omitempty"`
 573  }
 574  
 575  func loadState(path string) (*state, error) {
 576  	raw, err := os.ReadFile(path)
 577  	if errors.Is(err, os.ErrNotExist) {
 578  		return nil, nil
 579  	}
 580  	if err != nil {
 581  		return nil, err
 582  	}
 583  	var st state
 584  	if err := json.Unmarshal(raw, &st); err != nil {
 585  		return nil, fmt.Errorf("%s: %w", path, err)
 586  	}
 587  	return &st, nil
 588  }
 589  
 590  func saveState(path string, st *state) error {
 591  	st.Updated = time.Now().UTC().Format(time.RFC3339)
 592  	raw, err := json.MarshalIndent(st, "", "  ")
 593  	if err != nil {
 594  		return err
 595  	}
 596  	tmp := path + ".tmp"
 597  	if err := os.WriteFile(tmp, append(raw, '\n'), 0o644); err != nil {
 598  		return err
 599  	}
 600  	return os.Rename(tmp, path)
 601  }
 602  
 603  func printStatus(cfg *config, st *state) error {
 604  	out := struct {
 605  		Chain       string `json:"chain"`
 606  		Start       uint32 `json:"start"`
 607  		PublishedTo int64  `json:"published_to"`
 608  		Covered     int64  `json:"covered_blocks"`
 609  		Batches     int    `json:"batches"`
 610  		Updated     string `json:"updated"`
 611  		LastError   string `json:"last_error,omitempty"`
 612  	}{
 613  		Chain:   cfg.tag,
 614  		Start:   cfg.from,
 615  		Updated: "never",
 616  	}
 617  	if st != nil {
 618  		out.PublishedTo = st.PublishedTo
 619  		out.Start = st.Start
 620  		out.Batches = st.Batches
 621  		out.Updated = st.Updated
 622  		out.LastError = st.LastError
 623  	}
 624  	if out.PublishedTo >= int64(out.Start) {
 625  		out.Covered = out.PublishedTo - int64(out.Start) + 1
 626  	}
 627  	raw, err := json.MarshalIndent(out, "", "  ")
 628  	if err != nil {
 629  		return err
 630  	}
 631  	fmt.Println(string(raw))
 632  	return nil
 633  }
 634  
 635  // publisher owns one relay connection per URL.
 636  type publisher struct {
 637  	urls   []string
 638  	key    [32]byte
 639  	relays map[string]*relay.Client
 640  }
 641  
 642  func newPublisher(urls []string, key [32]byte) *publisher {
 643  	return &publisher{urls: urls, key: key, relays: make(map[string]*relay.Client)}
 644  }
 645  
 646  func (p *publisher) client(url string) (*relay.Client, error) {
 647  	if c, ok := p.relays[url]; ok {
 648  		select {
 649  		case <-c.Done():
 650  			// The connection ended; the next attempt opens a new one.
 651  			_ = c.Close()
 652  			delete(p.relays, url)
 653  		default:
 654  			return c, nil
 655  		}
 656  	}
 657  	transport, err := relay.DialTransport(url)
 658  	if err != nil {
 659  		return nil, err
 660  	}
 661  	c, err := relay.New(transport, p.key, relay.Options{RelayURL: url})
 662  	if err != nil {
 663  		return nil, err
 664  	}
 665  	p.relays[url] = c
 666  	return c, nil
 667  }
 668  
 669  // refused is a relay's refusal with the URL that produced it, keeping the
 670  // rejection typed so the retry policy can tell a permanent no from a busy
 671  // relay. Joining the messages into one string would lose that distinction, and
 672  // the first version did: a policy refusal was retried eight times with backoff.
 673  type refused struct {
 674  	url string
 675  	*relay.Rejection
 676  }
 677  
 678  func (r *refused) Error() string { return r.url + ": " + r.Rejection.Error() }
 679  
 680  func (r *refused) Unwrap() error { return r.Rejection }
 681  
 682  // publish sends one event to every relay. A relay that already holds it counts
 683  // as success: the event is there, which is the whole point, and a restart after
 684  // a partial backfill would otherwise never get past the first batch.
 685  func (p *publisher) publish(ctx context.Context, ev *nostr.Event) error {
 686  	var failed []string
 687  
 688  	var permanent error
 689  
 690  	for _, u := range p.urls {
 691  		c, err := p.client(u)
 692  
 693  		if err != nil {
 694  			failed = append(failed, u+": "+err.Error())
 695  
 696  			continue
 697  		}
 698  
 699  		err = c.Publish(ctx, ev)
 700  
 701  		if err == nil {
 702  			continue
 703  		}
 704  
 705  		var rejection *relay.Rejection
 706  
 707  		if errors.As(err, &rejection) {
 708  			if rejection.Duplicate() {
 709  				continue
 710  			}
 711  
 712  			if permanent == nil && !rejection.Retryable() {
 713  				permanent = &refused{url: u, Rejection: rejection}
 714  			}
 715  		}
 716  
 717  		failed = append(failed, u+": "+err.Error())
 718  	}
 719  
 720  	if permanent != nil {
 721  		return permanent
 722  	}
 723  
 724  	if len(failed) > 0 {
 725  		return errors.New(strings.Join(failed, "; "))
 726  	}
 727  
 728  	return nil
 729  }
 730  
 731  func (p *publisher) close() {
 732  	for _, c := range p.relays {
 733  		_ = c.Close()
 734  	}
 735  }
 736  
 737  // loadKey reads the identity, creating one when the file is absent. The pubkey
 738  // it prints is what the relay policy has to allow, so a first run tells the
 739  // operator what to paste.
 740  func loadKey(path string) ([32]byte, [32]byte, bool, error) {
 741  	raw, err := os.ReadFile(path)
 742  	if err == nil {
 743  		var key [32]byte
 744  		if err := nostr.Decode32(strings.TrimSpace(string(raw)), key[:]); err != nil {
 745  			return [32]byte{}, [32]byte{}, false, fmt.Errorf("%s: %w", path, err)
 746  		}
 747  		pub, ok := secp256k1.PubKey(key)
 748  		if !ok {
 749  			return [32]byte{}, [32]byte{}, false, fmt.Errorf("%s: not a usable secret key", path)
 750  		}
 751  		return key, pub, false, nil
 752  	}
 753  	if !errors.Is(err, os.ErrNotExist) {
 754  		return [32]byte{}, [32]byte{}, false, err
 755  	}
 756  
 757  	for {
 758  		var key [32]byte
 759  		if _, err := rand.Read(key[:]); err != nil {
 760  			return [32]byte{}, [32]byte{}, false, err
 761  		}
 762  		pub, ok := secp256k1.PubKey(key)
 763  		if !ok {
 764  			continue
 765  		}
 766  		if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
 767  			return [32]byte{}, [32]byte{}, false, err
 768  		}
 769  		if err := os.WriteFile(path, []byte(nostr.Hex(key[:])+"\n"), 0o600); err != nil {
 770  			return [32]byte{}, [32]byte{}, false, err
 771  		}
 772  		return key, pub, true, nil
 773  	}
 774  }
 775  
 776  func parseFlags(args []string) (*config, error) {
 777  	fs := flag.NewFlagSet("nostrino-filtercache", flag.ContinueOnError)
 778  	var (
 779  		nodeURL = fs.String("node", "", "node JSON-RPC endpoint, http://user:pass@host:port")
 780  		peerArg = fs.String("peer", "",
 781  			"P2P peer to follow when there is no RPC node (host:port), as the gateway's own peer")
 782  		noHeaders = fs.Bool("no-headers", false,
 783  			"publish blocks only; for a peer that will not serve headers from this anchor")
 784  		noFilters = fs.Bool("no-filters", false,
 785  			"publish headers and blocks only; for a peer that does not serve BIP157")
 786  		genesisFlag = fs.Bool("genesis", false,
 787  			"anchor the header chain at genesis rather than the profile's checkpoint")
 788  		cookie   = fs.String("cookie", "", "path to the node's .cookie file, when the URL carries no credentials")
 789  		chainArg = fs.String("chain", "btc", "chain profile name or alias: btc, xbt, blake, testnet3, regtest")
 790  		tagArg   = fs.String("tag", "",
 791  			"chain name the events and the block service use (default: the profile name)")
 792  		data        = fs.String("data", "", "data directory for progress and the identity (default filtercache-<chain>)")
 793  		from        = fs.String("from", "", "first height to publish; the default is the node tip on a fresh cache, so only new heights are published")
 794  		keyFile     = fs.String("key", "", "identity file (default <data>/identity.key)")
 795  		poll        = fs.Duration("poll", 10*time.Second, "how often to check the node for new blocks")
 796  		headers     = fs.Bool("headers", true, "publish one event per block header before its filters")
 797  		blockListen = fs.String("block-listen", "",
 798  			"serve raw blocks on this address (host:port); empty disables the service")
 799  		blockDir = fs.String("block-cache-dir", "",
 800  			"where cached blocks live (default <data>/blocks)")
 801  		blockBytes = fs.Int64("block-cache-bytes", blockcache.DefaultMaxBytes,
 802  			"how many bytes of blocks to keep; the oldest are evicted first")
 803  		blockPrefetch = fs.Int("block-prefetch", 2,
 804  			"prefetch the blocks this many heights behind the tip")
 805  		once     = fs.Bool("once", false, "run to the node's current tip and exit")
 806  		status   = fs.Bool("status", false, "print coverage and exit")
 807  		pubkey   = fs.Bool("pubkey", false, "print the identity's public key and exit")
 808  		attempts = fs.Int("attempts", 8, "publish attempts per batch before giving up")
 809  		relayArg stringList
 810  	)
 811  	fs.Var(&relayArg, "relay", "relay URL to publish to; repeat for more than one")
 812  	if err := fs.Parse(args); err != nil {
 813  		return nil, err
 814  	}
 815  
 816  	profile, err := chain.ByName(*chainArg)
 817  	if err != nil {
 818  		return nil, err
 819  	}
 820  
 821  	cfg := &config{
 822  		nodeURL:       *nodeURL,
 823  		cookie:        *cookie,
 824  		peer:          *peerArg,
 825  		genesisAnchor: *genesisFlag,
 826  		noFilters:     *noFilters,
 827  		noHeaders:     *noHeaders,
 828  		chain:         profile,
 829  		tag:           *tagArg,
 830  		relays:        relayArg,
 831  		data:          *data,
 832  		poll:          *poll,
 833  		headers:       *headers && !*noHeaders,
 834  		blockListen:   *blockListen, blockDir: *blockDir,
 835  		blockBytes: *blockBytes, blockPrefetch: *blockPrefetch,
 836  		once:     *once,
 837  		status:   *status,
 838  		pubkey:   *pubkey,
 839  		attempts: *attempts,
 840  	}
 841  	if cfg.tag == "" {
 842  		// The tag is the name the operator asked for, not the profile's canonical one: a
 843  		// client addresses a chain by the name it knows it by, and the profile is only the
 844  		// parameters behind that name. "blake" and "xbt" are one profile and two spellings,
 845  		// and the application uses the first, so a sidecar started with -chain blake must
 846  		// publish under blake.
 847  		cfg.tag = strings.ToLower(strings.TrimSpace(*chainArg))
 848  	}
 849  	if cfg.data == "" {
 850  		cfg.data = "filtercache-" + cfg.tag
 851  	}
 852  	if *keyFile == "" {
 853  		cfg.keyFile = filepath.Join(cfg.data, "identity.key")
 854  	} else {
 855  		cfg.keyFile = *keyFile
 856  	}
 857  
 858  	// A checkpoint is the lowest height whose filters a light client can use,
 859  	// so it is the natural floor for the cache as well: below it the client
 860  	// cannot verify anything, cached or not. A chain with no checkpoint starts
 861  	// at the node's tip on the first run, because publishing every filter since
 862  	// genesis is a different program.
 863  	// The tip is the default because a sidecar beside a gateway is there for the newest block;
 864  	// a backfill is a decision an operator makes with -from.
 865  	cfg.from = 0
 866  	if *from != "" {
 867  		n, err := parseHeight(*from)
 868  		if err != nil {
 869  			return nil, err
 870  		}
 871  		cfg.from = n
 872  		cfg.fromSet = true
 873  	}
 874  
 875  	if !cfg.status && !cfg.pubkey {
 876  		if cfg.nodeURL == "" && cfg.peer == "" {
 877  			return nil, errors.New("-node (JSON-RPC) or -peer (P2P) is required")
 878  		}
 879  		if len(cfg.relays) == 0 {
 880  			return nil, errors.New("-relay is required at least once")
 881  		}
 882  		for _, u := range cfg.relays {
 883  			if _, err := url.Parse(u); err != nil {
 884  				return nil, fmt.Errorf("relay %q: %w", u, err)
 885  			}
 886  		}
 887  	}
 888  	if cfg.attempts < 1 {
 889  		return nil, errors.New("-attempts must be at least 1")
 890  	}
 891  
 892  	return cfg, nil
 893  }
 894  
 895  func parseHeight(s string) (uint32, error) {
 896  	var n uint64
 897  	if _, err := fmt.Sscan(s, &n); err != nil || n > 0xffffffff {
 898  		return 0, fmt.Errorf("height %q is not a block height", s)
 899  	}
 900  	return uint32(n), nil
 901  }
 902  
 903  // stringList is a repeatable flag.
 904  type stringList []string
 905  
 906  func (s *stringList) String() string { return strings.Join(*s, ",") }
 907  
 908  func (s *stringList) Set(v string) error {
 909  	if v == "" {
 910  		return errors.New("empty value")
 911  	}
 912  	*s = append(*s, v)
 913  	return nil
 914  }
 915  
 916  // size renders a body size without pretending to be precise to the byte.
 917  func size(n int) string {
 918  	switch {
 919  	case n >= 1<<20:
 920  		return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
 921  	case n >= 1<<10:
 922  		return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10))
 923  	default:
 924  		return fmt.Sprintf("%d B", n)
 925  	}
 926  }
 927  
 928  func logf(format string, args ...any) {
 929  	fmt.Fprintf(os.Stderr, time.Now().UTC().Format("2006-01-02T15:04:05Z")+" "+format+"\n", args...)
 930  }
 931