// Command btcd-lite-serve answers a btcd-lite dataset over HTTP. // // btcd-lite-serve -chains btc,xbt -data ./data -listen 127.0.0.1:8080 // // It serves the blocks a fill has put in /blocks under the chunk contract // in docs/PLAN.md: a status document, a range's chunk names, and the chunks // themselves, each named by the hash of its bytes. One body store serves every // chain: a block the two chains share is stored once, and each chain's header // store gives it a height. It also builds each chain's UTXO and filter dataset // over those blocks and serves it at /v1/utxo//, so the two datasets a // client needs come from one address. // // Every request is logged, at info when it was refused or failed and at debug // when it succeeded, and a heartbeat line says what the process holds while it // runs. -log-level and -log-file are how a host nobody is watching is // diagnosable; SIGHUP reopens the file for a rotation. package main import ( "context" "crypto/ed25519" "encoding/hex" "flag" "fmt" "log" "net/http" "os" "os/signal" "path/filepath" "runtime" "strings" "syscall" "time" "git.smesh.lol/btcd-lite/internal/chains" "git.smesh.lol/btcd-lite/internal/filterstore" "git.smesh.lol/btcd-lite/internal/logging" "git.smesh.lol/btcd-lite/internal/serve" "git.smesh.lol/btcd-lite/internal/service" "git.smesh.lol/btcd-lite/internal/store" utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve" ) func main() { chainList := flag.String("chains", chains.Parent+","+chains.Fork, "comma-separated chains to serve: btc, xbt") chainName := flag.String("chain", "", "one chain to serve; an alias for a single-entry -chains") data := flag.String("data", "", "instance data directory") listen := flag.String("listen", "127.0.0.1:8080", "address to serve on") keyFile := flag.String("key", "", "Ed25519 seed file the published manifest is signed with") buildUTXO := flag.Bool("utxo", true, "build and serve the UTXO dataset and the filters") rebuild := flag.Bool("rebuild-utxo", false, "rebuild the dataset even when one is present") filtersOnly := flag.Bool("filters-only", false, "build the filters and stop, without the UTXO sets") 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") verifyFilters := flag.Bool("verify-filters", false, "recompute the filters from the bodies and compare them with what is stored") filtersTo := flag.Uint("filters-to", 0, "highest height to build or verify filters to, 0 for the chain tip") regtest := flag.Bool("regtest", false, "the chain's rules are the local test chain's") level := flag.String("log-level", "info", "debug, info, warn or error") logFile := flag.String("log-file", "", "append the log to this file; empty means stderr") heartbeat := flag.Duration("heartbeat", 5*time.Minute, "how often to write a status line; 0 disables it") flag.Parse() if *chainName != "" { *chainList = *chainName } if *data == "" { fmt.Fprintln(os.Stderr, "btcd-lite-serve: -data is required") os.Exit(2) } lvl, err := logging.ParseLevel(*level) if err != nil { fmt.Fprintln(os.Stderr, "btcd-lite-serve: -log-level:", err) os.Exit(2) } lg, err := logging.OpenFile(*logFile, lvl) if err != nil { fmt.Fprintln(os.Stderr, "btcd-lite-serve:", err) os.Exit(2) } defer lg.Close() names, err := chainListOf(*chainList) if err != nil { fatal(lg, "%v", err) } lg.Infof("start: chains=%s data=%s listen=%s regtest=%v log_level=%s heartbeat=%s", strings.Join(names, ","), *data, *listen, *regtest, lvl, *heartbeat) bodies, err := openBodies(*data, *verifyStore) if err != nil { fatal(lg, "blocks: %v", err) } defer bodies.Close() headers := make(map[string]*store.HeaderStore, len(names)) for _, name := range names { hs, err := store.NewHeaderStore(filepath.Join(*data, "headers", name)) if err != nil { fatal(lg, "headers %s: %v", name, err) } defer hs.Close() headers[name] = hs } view := serve.New(headers, bodies) if *keyFile != "" { seed, err := os.ReadFile(*keyFile) if err != nil { fatal(lg, "key: %v", err) } raw, err := hex.DecodeString(strings.TrimSpace(string(seed))) if err != nil || len(raw) != ed25519.SeedSize { fatal(lg, "key: %s is not a 32-byte hex seed", *keyFile) } view.Key = ed25519.NewKeyFromSeed(raw) } filters, err := filterstore.Open(filterstore.Dir(*data)) if err != nil { fatal(lg, "filters: %v", err) } defer filters.Close() view.Filters = filters mux := http.NewServeMux() service.Routes(mux, view) // The UTXO dataset is built from the same store and served beside the // chunks, so a client fetches blocks and checkpoints from one address. The // cadence is the chain's retarget interval, which is the one the plan // names; there is no flag for it. var datasets []utxoserve.Chain if *buildUTXO || *filtersOnly || *verifyFilters { interval := chains.ParentRetarget if *regtest { interval = chains.Regtest().Exported.Retarget } if *filtersOnly || *verifyFilters { // Filters alone: they need bodies, not the UTXO set, so a host that // cannot hold the set can still produce them. if err := buildFilters(*data, names, headers, bodies, filters, interval, headerTips(names, headers), *verifyFilters, uint32(*filtersTo), lg); err != nil { fatal(lg, "filters: %v", err) } lg.Infof("filters built; serving") } else { datasets = ensureUTXO(*data, names, headers, bodies, filters, interval, *rebuild, false, false, 0, lg) } for _, c := range datasets { mountUTXO(mux, c) } } srv := &http.Server{ Addr: *listen, Handler: lg.Handler(mux), ReadHeaderTimeout: 10 * time.Second, WriteTimeout: 10 * time.Minute, ErrorLog: log.New(lg.Writer(), "", log.LstdFlags), } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() go func() { <-ctx.Done() shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _ = srv.Shutdown(shutdown) }() lg.ReopenOnHangup() lg.SignalLevels(lvl) go lg.Heartbeat(ctx, *heartbeat, func() string { return report(lg, names, headers, bodies, filters, datasets) }) lg.Infof("serving: chains=%s blocks=%d filters=%d", strings.Join(names, ","), bodies.Len(), filters.Len()) if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { fatal(lg, "listen: %v", err) } lg.Infof("stopped") } // report is the heartbeat line: what the process holds and what it has served. func report(lg *logging.Logger, names []string, headers map[string]*store.HeaderStore, bodies *store.BlockStore, filters *filterstore.Store, datasets []utxoserve.Chain) string { st := lg.Stats() var b strings.Builder fmt.Fprintf(&b, "blocks=%d filters=%d requests=%d bytes_out=%d refused=%d failed=%d heap_mb=%d goroutines=%d", bodies.Len(), filters.Len(), st.Requests, st.Bytes, st.Refused, st.Failed, heapMB(), runtime.NumGoroutine()) for _, name := range names { tip, _, ok := headers[name].HeaderTip() fmt.Fprintf(&b, " %s_tip=%d", name, tipOf(tip, ok)) } for _, c := range datasets { idx, err := utxoserve.Open(c) if err != nil { fmt.Fprintf(&b, " %s_snapshot=none", c.Name) continue } points := idx.Points() fmt.Fprintf(&b, " %s_snapshot=%d", c.Name, points[len(points)-1]) } return b.String() } func tipOf(tip uint32, ok bool) uint32 { if !ok { return 0 } return tip } func heapMB() uint64 { var m runtime.MemStats runtime.ReadMemStats(&m) return m.HeapAlloc >> 20 } func fatal(lg *logging.Logger, format string, args ...any) { lg.Errorf(format, args...) os.Exit(1) } // openBodies opens the block store, verifying every block on disk only when the // operator asks for it: the pass is linear in the store, so a 600 GB dataset // takes hours to open and a restart costs the same. func openBodies(data string, verify bool) (*store.BlockStore, error) { if verify { return store.NewBlockStore(filepath.Join(data, "blocks")) } return store.NewBlockStoreTrusting(filepath.Join(data, "blocks")) } // headerTips is each chain's constructed tip, which is what a build covers. func headerTips(names []string, headers map[string]*store.HeaderStore) map[string]uint32 { tips := make(map[string]uint32, len(names)) for _, name := range names { if tip, _, ok := headers[name].HeaderTip(); ok { tips[name] = tip } } return tips } // chainListOf splits and checks a -chains flag. func chainListOf(s string) ([]string, error) { var out []string seen := map[string]bool{} for _, name := range strings.Split(s, ",") { name = strings.TrimSpace(name) if name == "" || seen[name] { continue } if _, err := chains.ByName(name); err != nil { return nil, err } seen[name] = true out = append(out, name) } if len(out) == 0 { return nil, fmt.Errorf("no chains named") } return out, nil }