main.go raw

   1  // Command btcd-lite-serve answers a btcd-lite dataset over HTTP.
   2  //
   3  //	btcd-lite-serve -chains btc,xbt -data ./data -listen 127.0.0.1:8080
   4  //
   5  // It serves the blocks a fill has put in <data>/blocks under the chunk contract
   6  // in docs/PLAN.md: a status document, a range's chunk names, and the chunks
   7  // themselves, each named by the hash of its bytes. One body store serves every
   8  // chain: a block the two chains share is stored once, and each chain's header
   9  // store gives it a height. It also builds each chain's UTXO and filter dataset
  10  // over those blocks and serves it at /v1/utxo/<chain>/, so the two datasets a
  11  // client needs come from one address.
  12  //
  13  // Every request is logged, at info when it was refused or failed and at debug
  14  // when it succeeded, and a heartbeat line says what the process holds while it
  15  // runs. -log-level and -log-file are how a host nobody is watching is
  16  // diagnosable; SIGHUP reopens the file for a rotation.
  17  package main
  18  
  19  import (
  20  	"context"
  21  	"crypto/ed25519"
  22  	"encoding/hex"
  23  	"flag"
  24  	"fmt"
  25  	"log"
  26  	"net/http"
  27  	"os"
  28  	"os/signal"
  29  	"path/filepath"
  30  	"runtime"
  31  	"strings"
  32  	"syscall"
  33  	"time"
  34  
  35  	"git.smesh.lol/btcd-lite/internal/chains"
  36  	"git.smesh.lol/btcd-lite/internal/filterstore"
  37  	"git.smesh.lol/btcd-lite/internal/logging"
  38  	"git.smesh.lol/btcd-lite/internal/serve"
  39  	"git.smesh.lol/btcd-lite/internal/service"
  40  	"git.smesh.lol/btcd-lite/internal/store"
  41  	utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve"
  42  )
  43  
  44  func main() {
  45  	chainList := flag.String("chains", chains.Parent+","+chains.Fork, "comma-separated chains to serve: btc, xbt")
  46  	chainName := flag.String("chain", "", "one chain to serve; an alias for a single-entry -chains")
  47  	data := flag.String("data", "", "instance data directory")
  48  	listen := flag.String("listen", "127.0.0.1:8080", "address to serve on")
  49  	keyFile := flag.String("key", "", "Ed25519 seed file the published manifest is signed with")
  50  	buildUTXO := flag.Bool("utxo", true, "build and serve the UTXO dataset and the filters")
  51  	rebuild := flag.Bool("rebuild-utxo", false, "rebuild the dataset even when one is present")
  52  	filtersOnly := flag.Bool("filters-only", false, "build the filters and stop, without the UTXO sets")
  53  	verifyStore := flag.Bool("verify-store", true, "read every stored block back when opening the store; false opens on the index alone and is what a dataset too big to scan needs")
  54  	verifyFilters := flag.Bool("verify-filters", false, "recompute the filters from the bodies and compare them with what is stored")
  55  	filtersTo := flag.Uint("filters-to", 0, "highest height to build or verify filters to, 0 for the chain tip")
  56  	regtest := flag.Bool("regtest", false, "the chain's rules are the local test chain's")
  57  	level := flag.String("log-level", "info", "debug, info, warn or error")
  58  	logFile := flag.String("log-file", "", "append the log to this file; empty means stderr")
  59  	heartbeat := flag.Duration("heartbeat", 5*time.Minute, "how often to write a status line; 0 disables it")
  60  	flag.Parse()
  61  	if *chainName != "" {
  62  		*chainList = *chainName
  63  	}
  64  	if *data == "" {
  65  		fmt.Fprintln(os.Stderr, "btcd-lite-serve: -data is required")
  66  		os.Exit(2)
  67  	}
  68  	lvl, err := logging.ParseLevel(*level)
  69  	if err != nil {
  70  		fmt.Fprintln(os.Stderr, "btcd-lite-serve: -log-level:", err)
  71  		os.Exit(2)
  72  	}
  73  	lg, err := logging.OpenFile(*logFile, lvl)
  74  	if err != nil {
  75  		fmt.Fprintln(os.Stderr, "btcd-lite-serve:", err)
  76  		os.Exit(2)
  77  	}
  78  	defer lg.Close()
  79  	names, err := chainListOf(*chainList)
  80  	if err != nil {
  81  		fatal(lg, "%v", err)
  82  	}
  83  	lg.Infof("start: chains=%s data=%s listen=%s regtest=%v log_level=%s heartbeat=%s",
  84  		strings.Join(names, ","), *data, *listen, *regtest, lvl, *heartbeat)
  85  	bodies, err := openBodies(*data, *verifyStore)
  86  	if err != nil {
  87  		fatal(lg, "blocks: %v", err)
  88  	}
  89  	defer bodies.Close()
  90  	headers := make(map[string]*store.HeaderStore, len(names))
  91  	for _, name := range names {
  92  		hs, err := store.NewHeaderStore(filepath.Join(*data, "headers", name))
  93  		if err != nil {
  94  			fatal(lg, "headers %s: %v", name, err)
  95  		}
  96  		defer hs.Close()
  97  		headers[name] = hs
  98  	}
  99  
 100  	view := serve.New(headers, bodies)
 101  	if *keyFile != "" {
 102  		seed, err := os.ReadFile(*keyFile)
 103  		if err != nil {
 104  			fatal(lg, "key: %v", err)
 105  		}
 106  		raw, err := hex.DecodeString(strings.TrimSpace(string(seed)))
 107  		if err != nil || len(raw) != ed25519.SeedSize {
 108  			fatal(lg, "key: %s is not a 32-byte hex seed", *keyFile)
 109  		}
 110  		view.Key = ed25519.NewKeyFromSeed(raw)
 111  	}
 112  	filters, err := filterstore.Open(filterstore.Dir(*data))
 113  	if err != nil {
 114  		fatal(lg, "filters: %v", err)
 115  	}
 116  	defer filters.Close()
 117  	view.Filters = filters
 118  	mux := http.NewServeMux()
 119  	service.Routes(mux, view)
 120  	// The UTXO dataset is built from the same store and served beside the
 121  	// chunks, so a client fetches blocks and checkpoints from one address. The
 122  	// cadence is the chain's retarget interval, which is the one the plan
 123  	// names; there is no flag for it.
 124  	var datasets []utxoserve.Chain
 125  	if *buildUTXO || *filtersOnly || *verifyFilters {
 126  		interval := chains.ParentRetarget
 127  		if *regtest {
 128  			interval = chains.Regtest().Exported.Retarget
 129  		}
 130  		if *filtersOnly || *verifyFilters {
 131  			// Filters alone: they need bodies, not the UTXO set, so a host that
 132  			// cannot hold the set can still produce them.
 133  			if err := buildFilters(*data, names, headers, bodies, filters, interval, headerTips(names, headers), *verifyFilters, uint32(*filtersTo), lg); err != nil {
 134  				fatal(lg, "filters: %v", err)
 135  			}
 136  			lg.Infof("filters built; serving")
 137  		} else {
 138  			datasets = ensureUTXO(*data, names, headers, bodies, filters, interval, *rebuild, false, false, 0, lg)
 139  		}
 140  		for _, c := range datasets {
 141  			mountUTXO(mux, c)
 142  		}
 143  	}
 144  	srv := &http.Server{
 145  		Addr:              *listen,
 146  		Handler:           lg.Handler(mux),
 147  		ReadHeaderTimeout: 10 * time.Second,
 148  		WriteTimeout:      10 * time.Minute,
 149  		ErrorLog:          log.New(lg.Writer(), "", log.LstdFlags),
 150  	}
 151  
 152  	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
 153  	defer stop()
 154  	go func() {
 155  		<-ctx.Done()
 156  		shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 157  		defer cancel()
 158  		_ = srv.Shutdown(shutdown)
 159  	}()
 160  	lg.ReopenOnHangup()
 161  	lg.SignalLevels(lvl)
 162  	go lg.Heartbeat(ctx, *heartbeat, func() string {
 163  		return report(lg, names, headers, bodies, filters, datasets)
 164  	})
 165  	lg.Infof("serving: chains=%s blocks=%d filters=%d", strings.Join(names, ","), bodies.Len(), filters.Len())
 166  	if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
 167  		fatal(lg, "listen: %v", err)
 168  	}
 169  	lg.Infof("stopped")
 170  }
 171  
 172  // report is the heartbeat line: what the process holds and what it has served.
 173  func report(lg *logging.Logger, names []string, headers map[string]*store.HeaderStore, bodies *store.BlockStore, filters *filterstore.Store, datasets []utxoserve.Chain) string {
 174  	st := lg.Stats()
 175  	var b strings.Builder
 176  	fmt.Fprintf(&b, "blocks=%d filters=%d requests=%d bytes_out=%d refused=%d failed=%d heap_mb=%d goroutines=%d",
 177  		bodies.Len(), filters.Len(), st.Requests, st.Bytes, st.Refused, st.Failed,
 178  		heapMB(), runtime.NumGoroutine())
 179  	for _, name := range names {
 180  		tip, _, ok := headers[name].HeaderTip()
 181  		fmt.Fprintf(&b, " %s_tip=%d", name, tipOf(tip, ok))
 182  	}
 183  	for _, c := range datasets {
 184  		idx, err := utxoserve.Open(c)
 185  		if err != nil {
 186  			fmt.Fprintf(&b, " %s_snapshot=none", c.Name)
 187  			continue
 188  		}
 189  		points := idx.Points()
 190  		fmt.Fprintf(&b, " %s_snapshot=%d", c.Name, points[len(points)-1])
 191  	}
 192  	return b.String()
 193  }
 194  
 195  func tipOf(tip uint32, ok bool) uint32 {
 196  	if !ok {
 197  		return 0
 198  	}
 199  	return tip
 200  }
 201  
 202  func heapMB() uint64 {
 203  	var m runtime.MemStats
 204  	runtime.ReadMemStats(&m)
 205  	return m.HeapAlloc >> 20
 206  }
 207  
 208  func fatal(lg *logging.Logger, format string, args ...any) {
 209  	lg.Errorf(format, args...)
 210  	os.Exit(1)
 211  }
 212  
 213  // openBodies opens the block store, verifying every block on disk only when the
 214  // operator asks for it: the pass is linear in the store, so a 600 GB dataset
 215  // takes hours to open and a restart costs the same.
 216  func openBodies(data string, verify bool) (*store.BlockStore, error) {
 217  	if verify {
 218  		return store.NewBlockStore(filepath.Join(data, "blocks"))
 219  	}
 220  	return store.NewBlockStoreTrusting(filepath.Join(data, "blocks"))
 221  }
 222  
 223  // headerTips is each chain's constructed tip, which is what a build covers.
 224  func headerTips(names []string, headers map[string]*store.HeaderStore) map[string]uint32 {
 225  	tips := make(map[string]uint32, len(names))
 226  	for _, name := range names {
 227  		if tip, _, ok := headers[name].HeaderTip(); ok {
 228  			tips[name] = tip
 229  		}
 230  	}
 231  	return tips
 232  }
 233  
 234  // chainListOf splits and checks a -chains flag.
 235  func chainListOf(s string) ([]string, error) {
 236  	var out []string
 237  	seen := map[string]bool{}
 238  	for _, name := range strings.Split(s, ",") {
 239  		name = strings.TrimSpace(name)
 240  		if name == "" || seen[name] {
 241  			continue
 242  		}
 243  		if _, err := chains.ByName(name); err != nil {
 244  			return nil, err
 245  		}
 246  		seen[name] = true
 247  		out = append(out, name)
 248  	}
 249  	if len(out) == 0 {
 250  		return nil, fmt.Errorf("no chains named")
 251  	}
 252  	return out, nil
 253  }
 254