1 // Package service is the HTTP face of one instance: what a second instance
2 // fills from and what a client asks about.
3 //
4 // The contract is small on purpose. Every chain artifact is content-addressed
5 // by double SHA-256 of its bytes, so a client verifies what it downloaded
6 // against the name it asked for and an instance can only withhold. A status
7 // document names what the instance holds and what it does not, and a chunk
8 // endpoint serves the bytes of one chunk.
9 //
10 // Nothing here trusts a chunk name from a client: a chunk is found through the
11 // manifest, so a chunk that is not in the index of the range it claims is not
12 // served under that name.
13 package service
14 15 import (
16 "encoding/json"
17 "fmt"
18 "net/http"
19 20 "git.smesh.lol/btcd-lite/internal/chunk"
21 )
22 23 // Chunks is the index a service serves from.
24 type Chunks interface {
25 // Status describes what the instance holds.
26 Status() Status
27 // Range returns the chunks of a kind and chain that cover [from,to) in
28 // height order, cut the way the chunker cut them.
29 Range(kind chunk.Kind, chain string, from, to uint32) ([]chunk.Chunk, error)
30 // Get returns the chunk filed under a name, if one is.
31 Get(name string) (chunk.Chunk, bool)
32 // Manifest returns the instance's signed inventory, if it publishes one.
33 // An instance that does not is answering ranges without a document that
34 // holds the chunks to them.
35 Manifest() ([]byte, bool)
36 }
37 38 // Status is the document a client reads first.
39 type Status struct {
40 // Chains maps a chain name to its coverage.
41 Chains map[string]Chain `json:"chains"`
42 // Blocks is how many block bodies the instance holds.
43 Blocks uint64 `json:"blocks"`
44 // Filters is how many compact filters the instance holds.
45 Filters uint64 `json:"filters,omitempty"`
46 // UTXO names the UTXO coverage, or is empty on an instance with none.
47 UTXO string `json:"utxo,omitempty"`
48 }
49 50 // Chain is one chain's coverage: the lowest height it holds and its tip.
51 type Chain struct {
52 Start uint32 `json:"start"`
53 Tip uint32 `json:"tip"`
54 }
55 56 // Handler returns the service's HTTP handler.
57 func Handler(c Chunks, opts ...Option) http.Handler {
58 mux := http.NewServeMux()
59 Routes(mux, c, opts...)
60 return mux
61 }
62 63 // WithUTXO adds the UTXO query endpoints to a service: one checkpoint chain per
64 // chain name. A chain absent from the map answers nothing, and the endpoint
65 // says which chains it has.
66 func WithUTXO(srcs map[string]UTXOSource) Option {
67 return func(o *options) { o.utxo = srcs }
68 }
69 70 // Option configures a service.
71 type Option func(*options)
72 73 type options struct {
74 utxo map[string]UTXOSource
75 }
76 77 // Routes registers the service's endpoints on a mux, so a process that also
78 // serves something else owns one mux.
79 func Routes(mux *http.ServeMux, c Chunks, opts ...Option) {
80 var o options
81 for _, opt := range opts {
82 opt(&o)
83 }
84 if len(o.utxo) > 0 {
85 routesUTXO(mux, o.utxo)
86 }
87 mux.HandleFunc("GET /v1/status", func(w http.ResponseWriter, r *http.Request) {
88 writeJSON(w, c.Status())
89 })
90 mux.HandleFunc("GET /v1/manifest", func(w http.ResponseWriter, r *http.Request) {
91 raw, ok := c.Manifest()
92 if !ok {
93 http.Error(w, "this instance publishes no manifest", http.StatusNotFound)
94 return
95 }
96 w.Header().Set("Content-Type", "application/json")
97 _, _ = w.Write(raw)
98 })
99 // The pattern language has no way to put two wildcards in one segment, so
100 // the range is split here: "100-200" is the segment the client sends.
101 mux.HandleFunc("GET /v1/chains/{chain}/{kind}/{range}", func(w http.ResponseWriter, r *http.Request) {
102 kind, ok := chunk.ParseKind(r.PathValue("kind"))
103 if !ok {
104 http.Error(w, "no such kind", http.StatusNotFound)
105 return
106 }
107 chain := r.PathValue("chain")
108 from, to, err := parseRange(r.PathValue("range"))
109 if err != nil {
110 http.Error(w, err.Error(), http.StatusBadRequest)
111 return
112 }
113 chunks, err := c.Range(kind, chain, from, to)
114 if err != nil {
115 http.Error(w, err.Error(), http.StatusBadRequest)
116 return
117 }
118 names := make([]string, len(chunks))
119 for i, ch := range chunks {
120 names[i] = ch.Name().String()
121 }
122 writeJSON(w, map[string]any{
123 "kind": kind.String(),
124 "chain": chain,
125 "from": from,
126 "to": to,
127 "chunks": names,
128 })
129 })
130 mux.HandleFunc("GET /v1/chunks/{name}", func(w http.ResponseWriter, r *http.Request) {
131 name := r.PathValue("name")
132 ch, ok := c.Get(name)
133 if !ok {
134 http.Error(w, "no such chunk", http.StatusNotFound)
135 return
136 }
137 // The bytes are served with their own name in the ETag, so a client
138 // that got them from a cache can tell it has the right ones.
139 w.Header().Set("ETag", `"`+name+`"`)
140 w.Header().Set("Content-Type", "application/octet-stream")
141 w.Header().Set("X-Chunk-Kind", ch.Kind.String())
142 w.Header().Set("X-Chunk-From", fmt.Sprint(ch.From))
143 w.Header().Set("X-Chunk-To", fmt.Sprint(ch.To))
144 _, _ = w.Write(ch.Raw)
145 })
146 }
147 148 func writeJSON(w http.ResponseWriter, v any) {
149 w.Header().Set("Content-Type", "application/json")
150 enc := json.NewEncoder(w)
151 enc.SetIndent("", " ")
152 _ = enc.Encode(v)
153 }
154 155 // parseRange reads the "from-to" segment.
156 func parseRange(seg string) (uint32, uint32, error) {
157 var a, b uint32
158 if _, err := fmt.Sscanf(seg, "%d-%d", &a, &b); err != nil {
159 return 0, 0, fmt.Errorf("range %q is not from-to", seg)
160 }
161 if b <= a {
162 return 0, 0, fmt.Errorf("range %d-%d is empty", a, b)
163 }
164 return a, b, nil
165 }
166