1 package service
2 3 import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7 "os"
8 "path/filepath"
9 "sort"
10 "strconv"
11 "strings"
12 "sync"
13 14 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
15 16 "git.smesh.lol/btcd-lite/internal/utxo"
17 utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
18 "git.smesh.lol/btcd-lite/internal/wire"
19 )
20 21 // UTXOSource answers the unspent set at a height: the entries sorted by
22 // outpoint, and the height of the nearest checkpoint at or below the one
23 // asked for when it differs.
24 //
25 // The service does not assume the set is small enough to hold at hand: it is
26 // read per checkpoint and cached, and a query above the highest checkpoint is
27 // answered from the highest one only if the caller says so.
28 type UTXOSource interface {
29 // Set returns every unspent entry at the nearest checkpoint at or below
30 // height.
31 Set(height uint32) ([]utxo.Entry, uint32, error)
32 // Checkpoints are the heights a set exists at, ascending.
33 Checkpoints() []uint32
34 }
35 36 // DiskUTXO is a checkpoint chain on disk, read on demand.
37 //
38 // Dirs are searched in order, which is how a chain's dataset is laid out: the
39 // shared prefix's snapshots first, the chain's own second. A height is a
40 // snapshot height if any directory holds it.
41 type DiskUTXO struct {
42 Dirs []string
43 44 mu sync.Mutex
45 cached uint32
46 have bool
47 set []utxo.Entry
48 }
49 50 // Checkpoints lists the snapshot heights across the directories.
51 func (d *DiskUTXO) Checkpoints() []uint32 {
52 seen := map[uint32]bool{}
53 var out []uint32
54 for _, dir := range d.Dirs {
55 entries, err := os.ReadDir(dir)
56 if err != nil {
57 continue
58 }
59 for _, e := range entries {
60 name := e.Name()
61 if !strings.HasPrefix(name, "set-") || !strings.HasSuffix(name, ".dat") {
62 continue
63 }
64 h, err := strconv.ParseUint(strings.TrimSuffix(strings.TrimPrefix(name, "set-"), ".dat"), 10, 32)
65 if err != nil || seen[uint32(h)] {
66 continue
67 }
68 seen[uint32(h)] = true
69 out = append(out, uint32(h))
70 }
71 }
72 sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
73 return out
74 }
75 76 // file returns the path of the set at a height, in whichever directory holds it.
77 func (d *DiskUTXO) file(height uint32) (string, bool) {
78 for _, dir := range d.Dirs {
79 path := filepath.Join(dir, utxostore.SetFile(height))
80 if _, err := os.Stat(path); err == nil {
81 return path, true
82 }
83 }
84 return "", false
85 }
86 87 // Set reads the checkpoint at or below height, caching the last one.
88 func (d *DiskUTXO) Set(height uint32) ([]utxo.Entry, uint32, error) {
89 points := d.Checkpoints()
90 if len(points) == 0 {
91 return nil, 0, fmt.Errorf("service: no checkpoints in %s", strings.Join(d.Dirs, ","))
92 }
93 at := points[0]
94 for _, p := range points {
95 if p <= height {
96 at = p
97 }
98 }
99 d.mu.Lock()
100 defer d.mu.Unlock()
101 if d.have && d.cached == at {
102 return d.set, at, nil
103 }
104 path, ok := d.file(at)
105 if !ok {
106 return nil, at, fmt.Errorf("service: no set file at %d", at)
107 }
108 raw, err := os.ReadFile(path)
109 if err != nil {
110 return nil, at, err
111 }
112 entries := make([]utxo.Entry, 0, len(raw)/utxostore.EntrySize)
113 buf := make([]byte, utxostore.EntrySize)
114 for i := 0; i+utxostore.EntrySize <= len(raw); i += utxostore.EntrySize {
115 copy(buf, raw[i:i+utxostore.EntrySize])
116 entries = append(entries, utxo.Decode(buf))
117 }
118 d.set, d.cached, d.have = entries, at, true
119 return entries, at, nil
120 }
121 122 // UTXOQuery is the POST body of the utxo query.
123 type UTXOQuery struct {
124 Outpoints []string `json:"outpoints"`
125 // Height is the height the question is asked at; null or absent is the
126 // tip of the checkpoint chain.
127 Height *uint32 `json:"height"`
128 }
129 130 // UTXOAnswer is one outpoint's answer.
131 type UTXOAnswer struct {
132 OutPoint string `json:"outpoint"`
133 // Unspent is whether the checkpoint's set holds it.
134 Unspent bool `json:"unspent"`
135 // Value and Height are the entry's own, when it is unspent.
136 Value int64 `json:"value,omitempty"`
137 Height uint32 `json:"created_height,omitempty"`
138 // Coinbase is set for a coinbase output.
139 Coinbase bool `json:"coinbase,omitempty"`
140 // AnsweredAt is the checkpoint the answer comes from. A query above the
141 // last checkpoint is answered at it, and the caller can see which.
142 AnsweredAt uint32 `json:"answered_at"`
143 }
144 145 // UTXOResponse is the answer to a query.
146 type UTXOResponse struct {
147 Chain string `json:"chain"`
148 Asked *uint32 `json:"asked_height,omitempty"`
149 At uint32 `json:"answered_at"`
150 Results []UTXOAnswer `json:"results"`
151 }
152 153 // routesUTXO registers the query endpoint on a mux, one chain per source.
154 func routesUTXO(mux *http.ServeMux, srcs map[string]UTXOSource) {
155 names := make([]string, 0, len(srcs))
156 for name := range srcs {
157 names = append(names, name)
158 }
159 sort.Strings(names)
160 mux.HandleFunc("POST /v1/chains/{chain}/utxo/query", func(w http.ResponseWriter, r *http.Request) {
161 chainName := r.PathValue("chain")
162 src, ok := srcs[chainName]
163 if !ok {
164 writeErr(w, http.StatusNotFound, fmt.Sprintf("this instance holds no UTXO data for %q; it has %s", chainName, strings.Join(names, ",")))
165 return
166 }
167 var q UTXOQuery
168 if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<20)).Decode(&q); err != nil {
169 writeErr(w, http.StatusBadRequest, err.Error())
170 return
171 }
172 if len(q.Outpoints) == 0 {
173 writeErr(w, http.StatusBadRequest, "no outpoints")
174 return
175 }
176 height := ^uint32(0)
177 if q.Height != nil {
178 height = *q.Height
179 }
180 set, at, err := src.Set(height)
181 if err != nil {
182 writeErr(w, http.StatusInternalServerError, err.Error())
183 return
184 }
185 resp := UTXOResponse{Chain: chainName, Asked: q.Height, At: at}
186 for _, op := range q.Outpoints {
187 want, err := parseOutPoint(op)
188 if err != nil {
189 writeErr(w, http.StatusBadRequest, err.Error())
190 return
191 }
192 e, ok := findEntry(set, want)
193 ans := UTXOAnswer{OutPoint: op, Unspent: ok, AnsweredAt: at}
194 if ok {
195 ans.Value, ans.Height, ans.Coinbase = e.Value, e.Height, e.Coinbase
196 }
197 resp.Results = append(resp.Results, ans)
198 }
199 writeJSON(w, resp)
200 })
201 mux.HandleFunc("GET /v1/chains/{chain}/utxo/checkpoints", func(w http.ResponseWriter, r *http.Request) {
202 chainName := r.PathValue("chain")
203 src, ok := srcs[chainName]
204 if !ok {
205 writeErr(w, http.StatusNotFound, fmt.Sprintf("this instance holds no UTXO data for %q; it has %s", chainName, strings.Join(names, ",")))
206 return
207 }
208 writeJSON(w, map[string]any{"chain": chainName, "checkpoints": src.Checkpoints()})
209 })
210 }
211 212 // writeErr answers with a status and a reason.
213 func writeErr(w http.ResponseWriter, code int, msg string) {
214 w.Header().Set("Content-Type", "application/json")
215 w.WriteHeader(code)
216 _ = json.NewEncoder(w).Encode(map[string]string{"error": msg})
217 }
218 219 // parseOutPoint reads a txid:vout the way the protocol prints it.
220 func parseOutPoint(s string) (wire.OutPoint, error) {
221 i := strings.LastIndexByte(s, ':')
222 if i <= 0 {
223 return wire.OutPoint{}, fmt.Errorf("an outpoint is txid:vout")
224 }
225 h, err := chainhash.NewHashFromStr(s[:i])
226 if err != nil {
227 return wire.OutPoint{}, fmt.Errorf("%q is not txid:vout", s)
228 }
229 v, err := strconv.ParseUint(s[i+1:], 10, 32)
230 if err != nil {
231 return wire.OutPoint{}, fmt.Errorf("%q is not txid:vout", s)
232 }
233 return wire.OutPoint{Hash: *h, Index: uint32(v)}, nil
234 }
235 236 // findEntry is a binary search over the entries' sort order.
237 func findEntry(set []utxo.Entry, op wire.OutPoint) (utxo.Entry, bool) {
238 i := sort.Search(len(set), func(i int) bool { return !utxo.LessEntry(set[i], utxo.Entry{OutPoint: op}) })
239 if i < len(set) && set[i].OutPoint == op {
240 return set[i], true
241 }
242 return utxo.Entry{}, false
243 }
244