// Package service is the HTTP face of one instance: what a second instance // fills from and what a client asks about. // // The contract is small on purpose. Every chain artifact is content-addressed // by double SHA-256 of its bytes, so a client verifies what it downloaded // against the name it asked for and an instance can only withhold. A status // document names what the instance holds and what it does not, and a chunk // endpoint serves the bytes of one chunk. // // Nothing here trusts a chunk name from a client: a chunk is found through the // manifest, so a chunk that is not in the index of the range it claims is not // served under that name. package service import ( "encoding/json" "fmt" "net/http" "git.smesh.lol/btcd-lite/internal/chunk" ) // Chunks is the index a service serves from. type Chunks interface { // Status describes what the instance holds. Status() Status // Range returns the chunks of a kind and chain that cover [from,to) in // height order, cut the way the chunker cut them. Range(kind chunk.Kind, chain string, from, to uint32) ([]chunk.Chunk, error) // Get returns the chunk filed under a name, if one is. Get(name string) (chunk.Chunk, bool) // Manifest returns the instance's signed inventory, if it publishes one. // An instance that does not is answering ranges without a document that // holds the chunks to them. Manifest() ([]byte, bool) } // Status is the document a client reads first. type Status struct { // Chains maps a chain name to its coverage. Chains map[string]Chain `json:"chains"` // Blocks is how many block bodies the instance holds. Blocks uint64 `json:"blocks"` // Filters is how many compact filters the instance holds. Filters uint64 `json:"filters,omitempty"` // UTXO names the UTXO coverage, or is empty on an instance with none. UTXO string `json:"utxo,omitempty"` } // Chain is one chain's coverage: the lowest height it holds and its tip. type Chain struct { Start uint32 `json:"start"` Tip uint32 `json:"tip"` } // Handler returns the service's HTTP handler. func Handler(c Chunks, opts ...Option) http.Handler { mux := http.NewServeMux() Routes(mux, c, opts...) return mux } // WithUTXO adds the UTXO query endpoints to a service: one checkpoint chain per // chain name. A chain absent from the map answers nothing, and the endpoint // says which chains it has. func WithUTXO(srcs map[string]UTXOSource) Option { return func(o *options) { o.utxo = srcs } } // Option configures a service. type Option func(*options) type options struct { utxo map[string]UTXOSource } // Routes registers the service's endpoints on a mux, so a process that also // serves something else owns one mux. func Routes(mux *http.ServeMux, c Chunks, opts ...Option) { var o options for _, opt := range opts { opt(&o) } if len(o.utxo) > 0 { routesUTXO(mux, o.utxo) } mux.HandleFunc("GET /v1/status", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, c.Status()) }) mux.HandleFunc("GET /v1/manifest", func(w http.ResponseWriter, r *http.Request) { raw, ok := c.Manifest() if !ok { http.Error(w, "this instance publishes no manifest", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") _, _ = w.Write(raw) }) // The pattern language has no way to put two wildcards in one segment, so // the range is split here: "100-200" is the segment the client sends. mux.HandleFunc("GET /v1/chains/{chain}/{kind}/{range}", func(w http.ResponseWriter, r *http.Request) { kind, ok := chunk.ParseKind(r.PathValue("kind")) if !ok { http.Error(w, "no such kind", http.StatusNotFound) return } chain := r.PathValue("chain") from, to, err := parseRange(r.PathValue("range")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } chunks, err := c.Range(kind, chain, from, to) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } names := make([]string, len(chunks)) for i, ch := range chunks { names[i] = ch.Name().String() } writeJSON(w, map[string]any{ "kind": kind.String(), "chain": chain, "from": from, "to": to, "chunks": names, }) }) mux.HandleFunc("GET /v1/chunks/{name}", func(w http.ResponseWriter, r *http.Request) { name := r.PathValue("name") ch, ok := c.Get(name) if !ok { http.Error(w, "no such chunk", http.StatusNotFound) return } // The bytes are served with their own name in the ETag, so a client // that got them from a cache can tell it has the right ones. w.Header().Set("ETag", `"`+name+`"`) w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("X-Chunk-Kind", ch.Kind.String()) w.Header().Set("X-Chunk-From", fmt.Sprint(ch.From)) w.Header().Set("X-Chunk-To", fmt.Sprint(ch.To)) _, _ = w.Write(ch.Raw) }) } func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) enc.SetIndent("", " ") _ = enc.Encode(v) } // parseRange reads the "from-to" segment. func parseRange(seg string) (uint32, uint32, error) { var a, b uint32 if _, err := fmt.Sscanf(seg, "%d-%d", &a, &b); err != nil { return 0, 0, fmt.Errorf("range %q is not from-to", seg) } if b <= a { return 0, 0, fmt.Errorf("range %d-%d is empty", a, b) } return a, b, nil }