// Command btcd-lited is one instance: a data directory served over HTTP, a // relay for its chains' client transactions, and optionally a fill from a peer // over BIP324 and a seed from another instance's service. // // btcd-lited -chains btc,xbt -data ./data -listen 127.0.0.1:8080 \ // -peer btc=127.0.0.1:8333,xbt=127.0.0.1:8333 // // One process holds both chains over one body store: the blocks the two chains // share are stored once, and each chain's header store is the index that gives // them heights. With -peer it syncs each chain's header chain over p2p and // fills the body store from the same peer, over one connection per chain. With // -relay it takes client transactions at POST /v1/chains/{chain}/tx and // announces them to the peers it is given for that purpose. The HTTP service is // a view of the data directory and does not depend on either. package main import ( "context" "crypto/ed25519" "encoding/hex" "encoding/json" "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/filler" "git.smesh.lol/btcd-lite/internal/filterstore" "git.smesh.lol/btcd-lite/internal/filtersync" "git.smesh.lol/btcd-lite/internal/litedial" "git.smesh.lol/btcd-lite/internal/logging" "git.smesh.lol/btcd-lite/internal/process" "git.smesh.lol/btcd-lite/internal/relay" "git.smesh.lol/btcd-lite/internal/serve" "git.smesh.lol/btcd-lite/internal/service" "git.smesh.lol/btcd-lite/internal/staging" "git.smesh.lol/btcd-lite/internal/store" utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve" "git.smesh.lol/btcd-lite/internal/v2peer" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/neutrino" ) func main() { chainList := flag.String("chains", chains.Parent+","+chains.Fork, "comma-separated chains to hold: btc, xbt") chainName := flag.String("chain", "", "one chain to hold; an alias for a single-entry -chains") data := flag.String("data", "", "instance data directory") listen := flag.String("listen", "127.0.0.1:8080", "HTTP listen address") peerList := flag.String("peer", "", "p2p peers to fill from, as chain=host:port entries") relayList := flag.String("relay", "", "p2p peers to announce transactions to, as chain=host:port entries") keyFile := flag.String("key", "", "Ed25519 seed file the published manifest is signed with") regtest := flag.Bool("regtest", false, "use the local test chain's genesis and parameters") processAfter := flag.Bool("process-after-fill", true, "process the staging log after a fill") processOnly := flag.Bool("process-only", false, "process the staging log and serve, dialling no peers") 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") fillProgress := flag.Duration("fill-progress", time.Minute, "how often to write a fill progress line; 0 disables it") useV2 := flag.Bool("v2", false, "use BIP324 (v2) transport; plaintext v1 is the default because the v2 path closes connections part way through a sync against some real peers") // Off by default: a synced fold is anchored by whichever peer served it, // because the block headers do not commit to the filter chain. The dataset // builder computes filters from bodies instead, which needs no peer. 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") doFilters := flag.Bool("filters", false, "sync the BIP157 filter chain from the peer instead of computing it") filtersOnly := flag.Bool("filters-only", false, "sync filters and stop; no block fill") flag.Parse() if *chainName != "" { *chainList = *chainName } names, err := chainListOf(*chainList) if err != nil { fmt.Fprintf(os.Stderr, "btcd-lited: %v\n", err) os.Exit(2) } peers, err := peersOf(*peerList, names) if err != nil { fmt.Fprintf(os.Stderr, "btcd-lited: -peer: %v\n", err) os.Exit(2) } relayPeers, err := peersOf(*relayList, names) if err != nil { fmt.Fprintf(os.Stderr, "btcd-lited: -relay: %v\n", err) os.Exit(2) } if *data == "" { fmt.Fprintln(os.Stderr, "btcd-lited: -data is required") os.Exit(2) } lvl, err := logging.ParseLevel(*level) if err != nil { fmt.Fprintln(os.Stderr, "btcd-lited: -log-level:", err) os.Exit(2) } lg, err := logging.OpenFile(*logFile, lvl) if err != nil { fmt.Fprintln(os.Stderr, "btcd-lited:", err) os.Exit(2) } defer lg.Close() // What the process was asked to do, before it does any of it. A run that // leaves no trace of its own arguments is a run that cannot be told apart // from one that never started. startup := map[string]any{ "version": "btcd-lited", "chains": names, "data": *data, "listen": *listen, "peers": peers, "relay_peers": relayPeers, "key": *keyFile != "", "regtest": *regtest, "process_after_fill": *processAfter, "process_only": *processOnly, "log_level": lvl.String(), "heartbeat": heartbeat.String(), } if raw, err := json.Marshal(startup); err == nil { lg.Infof("start %s", raw) } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() if os.Getenv("BTCD_LITE_TRACE") != "" { v2peer.SetTrace(func(f string, a ...any) { log.Printf(f, a...) }) } cfg := instanceConfig{ chains: names, data: *data, listen: *listen, peers: peers, relayPeers: relayPeers, keyFile: *keyFile, regtest: *regtest, processAfter: *processAfter, processOnly: *processOnly, log: lg, heartbeat: *heartbeat, fillProgress: *fillProgress, v2: *useV2, filters: *doFilters, filtersOnly: *filtersOnly, verifyStore: *verifyStore, } lg.ReopenOnHangup() lg.SignalLevels(lvl) if err := run(ctx, cfg); err != nil { lg.Errorf("%v", err) os.Exit(1) } } type instanceConfig struct { chains []string data, listen string peers, relayPeers map[string][]string keyFile string regtest bool processAfter bool processOnly bool log *logging.Logger heartbeat time.Duration fillProgress time.Duration v2 bool verifyStore bool filters bool filtersOnly bool } func run(ctx context.Context, c instanceConfig) error { lg := c.log info := make(map[string]chains.Chain, len(c.chains)) for _, name := range c.chains { ci, err := chains.ByName(name) if err != nil { return err } if c.regtest { ci = chains.Regtest() ci.Name = name } info[name] = ci } // The fill connections are dialed before any store is opened. This is the // one variable left in a disagreement that cost many rounds: the same // dialler and the same arguments completed in thirteen milliseconds from a // test binary and stalled for the node's whole handshake timeout when the // instance called it after opening its stores. Dialing first removes the // variable; if the instance still stalls, the difference is not in what // runs before the dial. conns := make(map[string]*v2peer.Peer, len(c.chains)) connAddr := make(map[string]string, len(c.chains)) for _, name := range c.chains { if c.processOnly { break } // The header chain comes from the first peer that answers with the // service this instance needs, and every configured address is tried // before the fill is given up on: a peer that accepts TCP and then does // not speak has to fail without stopping the chain. var fallback *v2peer.Peer var fallbackAddr string for _, addr := range c.peers[name] { lg.Infof("fill %s: dialling %s", name, addr) // Twenty seconds for the handshake, not two minutes: a peer that // accepts TCP and then says nothing is one of eight, and the walk // has to get past it to the one that answers. peer, err := litedial.Connect(ctx, addr, "/btcd-lite:0.1.0/", info[name].WireMagic(), 20*time.Second, c.v2, lg.Logf) if err != nil { lg.Errorf("fill %s: %s: %v", name, addr, err) continue } // A peer that serves compact filters is preferred for the header // chain, because the filter sync runs over this connection and a // node that does not advertise the service disconnects a peer that // asks. The first peer that answers is kept as a fallback. if peer.Services()&nodeCompactFilters != 0 { if fallback != nil { _ = fallback.Close() } conns[name], connAddr[name] = peer, addr lg.Infof("fill %s: %s serves compact filters", name, addr) break } if fallback == nil { fallback, fallbackAddr = peer, addr lg.Infof("fill %s: %s does not serve compact filters, looking for one that does", name, addr) continue } _ = peer.Close() } if _, ok := conns[name]; !ok && fallback != nil { conns[name], connAddr[name] = fallback, fallbackAddr } } bodies, err := openBodies(c.data, c.verifyStore) if err != nil { return fmt.Errorf("blocks: %w", err) } defer bodies.Close() headers := make(map[string]*store.HeaderStore, len(c.chains)) view := serve.New(headers, bodies) for _, name := range c.chains { hs, err := store.NewHeaderStore(filepath.Join(c.data, "headers", name)) if err != nil { return fmt.Errorf("headers %s: %w", name, err) } defer hs.Close() headers[name] = hs genesis, err := info[name].Genesis() if err != nil { return err } if _, _, ok := hs.HeaderTip(); !ok { // A fresh store starts at the chain's genesis, which is the one // header a peer's first answer links to. if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: genesis.BlockHash(), FilterHeight: -1}); err != nil { return fmt.Errorf("anchor %s: %w", name, err) } if err := hs.PutHeaders(0, []btcwire.BlockHeader{genesis}); err != nil { return fmt.Errorf("seed genesis %s: %w", name, err) } } } if c.keyFile != "" { key, err := readKey(c.keyFile) if err != nil { return err } view.Key = key } filters, err := filterstore.Open(filterstore.Dir(c.data)) if err != nil { return fmt.Errorf("filters: %w", err) } defer filters.Close() staged := make(map[string]*staging.Log, len(c.chains)) for _, name := range c.chains { l, err := staging.Open(staging.Dir(c.data, name)) if err != nil { return fmt.Errorf("staging %s: %w", name, err) } defer l.Close() staged[name] = l } for _, name := range c.chains { peer, ok := conns[name] if !ok { if len(c.peers[name]) > 0 { lg.Warnf("fill %s: no connection to any of %d peers, serving what the data directory holds", name, len(c.peers[name])) } else { lg.Infof("fill %s: no peer given, serving what the data directory holds", name) } continue } if err := fill(ctx, info[name], headers[name], filters, bodies, staged[name], c.peers[name], connAddr[name], peer, lg, c.fillProgress, c.v2, c.filters, c.filtersOnly); err != nil && ctx.Err() == nil { lg.Errorf("fill %s: %v", name, err) } } if c.processAfter { for _, name := range c.chains { if err := runProcess(c.data, name, staged[name], headers[name], bodies, lg); err != nil { lg.Errorf("process %s: %v", name, err) } } } handlers := map[string]*relay.Handler{} for _, name := range c.chains { addrs := c.relayPeers[name] if len(addrs) == 0 { continue } window := relay.NewWindow(128 << 20) rel, err := relay.New(relay.RelayConfig{Profile: info[name].Profile, Window: window, Peers: addrs, V2: c.v2, Logf: lg.Logf}) if err != nil { return err } go rel.Start(ctx) go rel.Follow(ctx, headers[name], nil, 15*time.Second) go rel.Rebroadcast(ctx, 45*time.Minute) handlers[name] = &relay.Handler{Chain: name, Relay: rel, Window: window} } view.Filters = filters mux := http.NewServeMux() service.Routes(mux, view, service.WithUTXO(utxoSources(c.data, c.chains))) for _, name := range c.chains { sets, diffs := utxoDirs(c.data, name) utxoserve.Routes(mux, utxoserve.Chain{Name: name, Sets: sets, Diffs: diffs, Interval: info[name].Exported.Retarget}) } if len(handlers) > 0 { relay.Multi(mux, handlers) } srv := &http.Server{ Addr: c.listen, Handler: lg.Handler(mux), ReadHeaderTimeout: 10 * time.Second, WriteTimeout: 10 * time.Minute, ErrorLog: log.New(lg.Writer(), "", log.LstdFlags), } go func() { <-ctx.Done() shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _ = srv.Shutdown(shutdown) }() lg.Infof("serving: chains=%s data=%s listen=%s blocks=%d filters=%d relays=%d", strings.Join(c.chains, ","), c.data, c.listen, bodies.Len(), filters.Len(), len(handlers)) go lg.Heartbeat(ctx, c.heartbeat, func() string { return report(lg, c.chains, headers, bodies, filters, staged) }) if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { return err } return nil } // runProcess turns one chain's staging log into stored blocks. func runProcess(data, name string, staged *staging.Log, headers *store.HeaderStore, bodies *store.BlockStore, lg *logging.Logger) error { if staged.Len() == 0 { lg.Infof("process %s: nothing staged", name) return nil } res, err := process.Run(process.Config{ Chain: name, Staging: staged, Bodies: bodies, Headers: headers, Missing: process.MissingName(data, name), Logf: lg.Logf, }) if err != nil { return err } if res.Dropped > 0 { lg.Warnf("process %s: %d bodies refused, recorded in %s", name, res.Dropped, process.MissingName(data, name)) } return nil } // utxoDirs is where one chain's dataset lives: the shared prefix's snapshots // and diffs first, the chain's own second. func utxoDirs(data, chainName string) (sets, diffs []string) { utxo := filepath.Join(data, "utxo") return []string{filepath.Join(utxo, "canonical"), filepath.Join(utxo, "chain-"+chainName)}, []string{filepath.Join(utxo, "diff", "shared"), filepath.Join(utxo, "diff", chainName)} } // utxoSources is the checkpoint chain in each chain's directory, if one is // there. An instance that holds no UTXO data answers no query for that chain. func utxoSources(data string, names []string) map[string]service.UTXOSource { out := make(map[string]service.UTXOSource, len(names)) for _, name := range names { sets, _ := utxoDirs(data, name) out[name] = &service.DiskUTXO{Dirs: sets} } return out } // fill syncs headers and then bodies over one connection per chain, because a // node refuses a second connection from the same address seconds after the // first. func fill(ctx context.Context, chainInfo chains.Chain, headers *store.HeaderStore, filterStore *filterstore.Store, bodies *store.BlockStore, staged *staging.Log, addrs []string, connected string, p *v2peer.Peer, lg *logging.Logger, progress time.Duration, useV2, doFilters, filtersOnly bool) error { tip, tipHash, _ := headers.HeaderTip() lg.Infof("fill %s: syncing headers from %d (%x)", chainInfo.Name, tip, [32]byte(tipHash)) if err := p.SyncHeaders(headers, lg.Logf); err != nil { // A peer that drops the connection after the handshake costs one // connection, not the fill: the blocks that need filling are the ones // above the headers this instance already holds, and the pool opens its // own lanes. if tip, _, ok := headers.HeaderTip(); !ok { _ = p.Close() return fmt.Errorf("headers: %w", err) } else { lg.Errorf("fill %s: headers: %v (continuing from %d)", chainInfo.Name, err, tip) } } if tip, _, ok := headers.HeaderTip(); ok { lg.Infof("fill %s: headers to %d", chainInfo.Name, tip) } // The filter chain comes next, over the same connection, before the fill // takes it: a filter is committed by the header chain, so fetching it and // checking it against the fold is the same guarantee as building it, and it // needs neither the UTXO set nor the scripts in memory. if doFilters { // A node decides whether to answer from its own services, and a node // that does not advertise compact filters disconnects the peer that // asks. So the bit is the gate for asking at all. if p.Services()&nodeCompactFilters == 0 { lg.Warnf("fill %s: %s does not serve compact filters, so none are synced", chainInfo.Name, connected) } else { start := time.Now() res, err := filtersync.Sync(ctx, p, headers, filterStore, lg.Logf) if err != nil { lg.Errorf("filters %s: %v", chainInfo.Name, err) } else { lg.Infof("filters %s: %d from %d to %d in %s", chainInfo.Name, res.Filters, res.From, res.To, time.Since(start).Round(time.Second)) } } } if filtersOnly { return nil } peers := make([]filler.Peer, 0, len(addrs)) for _, a := range addrs { peers = append(peers, filler.Peer{Addr: a}) } pool, err := filler.NewPool(filler.PoolConfig{ Chain: chainInfo.Name, Profile: chainInfo.Profile, Headers: headers, Bodies: bodies, Staging: staged, Peers: peers, Lanes: len(peers), V2: useV2, Logf: lg.Logf, Tracef: lg.Tracef, Warnf: lg.Warnf, ProgressEvery: progress, }) if err != nil { _ = p.Close() return err } if err := p.Err(); err == nil { pool.Reuse(connected, p) } else { lg.Warnf("fill %s: %s ended after the handshake (%v), lanes will dial", chainInfo.Name, connected, err) _ = p.Close() } start := time.Now() if err := pool.Run(ctx); err != nil { return fmt.Errorf("blocks: %w", err) } elapsed := time.Since(start) rate := float64(pool.Done()) / elapsed.Seconds() lg.Infof("fill %s: %d bodies in %s (%.0f/s) from %d peer(s), %d failed", chainInfo.Name, pool.Done(), elapsed.Round(time.Millisecond), rate, len(peers), pool.Failed()) return pool.Close() } // 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 == "" { continue } if 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 } // peersOf reads a peer flag into one address list per chain. // // The form is chain=host:port, because a two-chain instance fills from two // different nodes and the address alone does not say which chain it serves. On // a single-chain instance a bare address is that chain's, which keeps the // one-chain command line short. func peersOf(s string, names []string) (map[string][]string, error) { out := map[string][]string{} for _, e := range strings.Split(s, ",") { e = strings.TrimSpace(e) if e == "" { continue } chain, addr, ok := strings.Cut(e, "=") if !ok { if len(names) != 1 { return nil, fmt.Errorf("%q names no chain; write chain=host:port on an instance with %d chains", e, len(names)) } out[names[0]] = append(out[names[0]], e) continue } chain, addr = strings.TrimSpace(chain), strings.TrimSpace(addr) known := false for _, n := range names { if n == chain { known = true break } } if !known { return nil, fmt.Errorf("%q is not one of this instance's chains (%s)", chain, strings.Join(names, ",")) } out[chain] = append(out[chain], addr) } return out, nil } func readKey(path string) (ed25519.PrivateKey, error) { seed, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("key: %w", err) } raw, err := hex.DecodeString(strings.TrimSpace(string(seed))) if err != nil || len(raw) != ed25519.SeedSize { return nil, fmt.Errorf("key: %s is not a 32-byte hex seed", path) } return ed25519.NewKeyFromSeed(raw), nil } // openBodies opens the block store, verifying every block on disk only when the // operator asks: the pass is linear in the store, so a 600 GB dataset takes // hours to open and every restart pays it again. 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")) } // nodeCompactFilters is NODE_COMPACT_FILTERS: a peer sets it when it will answer // getcfheaders and getcfilters. btcd's wire package carries the messages and not // this flag. const nodeCompactFilters uint64 = 1 << 6 // 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, staged map[string]*staging.Log) string { st := lg.Stats() var stagedBodies int var stagedBytes int64 for _, name := range names { if l, ok := staged[name]; ok { stagedBodies += l.Len() stagedBytes += l.Bytes() } } var b strings.Builder fmt.Fprintf(&b, "blocks=%d filters=%d staged=%d staged_bytes=%d requests=%d bytes_out=%d refused=%d failed=%d heap_mb=%d goroutines=%d", bodies.Len(), filters.Len(), stagedBodies, stagedBytes, st.Requests, st.Bytes, st.Refused, st.Failed, heapMB(), runtime.NumGoroutine()) for _, name := range names { if tip, _, ok := headers[name].HeaderTip(); ok { fmt.Fprintf(&b, " %s_tip=%d", name, tip) } else { fmt.Fprintf(&b, " %s_tip=none", name) } } return b.String() } // heapMB is the live heap, which is the number that says whether a running // instance is growing without bound. func heapMB() uint64 { var m runtime.MemStats runtime.ReadMemStats(&m) return m.HeapAlloc >> 20 }