package service import ( "encoding/json" "fmt" "net/http" "os" "path/filepath" "sort" "strconv" "strings" "sync" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/utxo" utxostore "git.smesh.lol/btcd-lite/internal/utxo/store" "git.smesh.lol/btcd-lite/internal/wire" ) // UTXOSource answers the unspent set at a height: the entries sorted by // outpoint, and the height of the nearest checkpoint at or below the one // asked for when it differs. // // The service does not assume the set is small enough to hold at hand: it is // read per checkpoint and cached, and a query above the highest checkpoint is // answered from the highest one only if the caller says so. type UTXOSource interface { // Set returns every unspent entry at the nearest checkpoint at or below // height. Set(height uint32) ([]utxo.Entry, uint32, error) // Checkpoints are the heights a set exists at, ascending. Checkpoints() []uint32 } // DiskUTXO is a checkpoint chain on disk, read on demand. // // Dirs are searched in order, which is how a chain's dataset is laid out: the // shared prefix's snapshots first, the chain's own second. A height is a // snapshot height if any directory holds it. type DiskUTXO struct { Dirs []string mu sync.Mutex cached uint32 have bool set []utxo.Entry } // Checkpoints lists the snapshot heights across the directories. func (d *DiskUTXO) Checkpoints() []uint32 { seen := map[uint32]bool{} var out []uint32 for _, dir := range d.Dirs { entries, err := os.ReadDir(dir) if err != nil { continue } for _, e := range entries { name := e.Name() if !strings.HasPrefix(name, "set-") || !strings.HasSuffix(name, ".dat") { continue } h, err := strconv.ParseUint(strings.TrimSuffix(strings.TrimPrefix(name, "set-"), ".dat"), 10, 32) if err != nil || seen[uint32(h)] { continue } seen[uint32(h)] = true out = append(out, uint32(h)) } } sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) return out } // file returns the path of the set at a height, in whichever directory holds it. func (d *DiskUTXO) file(height uint32) (string, bool) { for _, dir := range d.Dirs { path := filepath.Join(dir, utxostore.SetFile(height)) if _, err := os.Stat(path); err == nil { return path, true } } return "", false } // Set reads the checkpoint at or below height, caching the last one. func (d *DiskUTXO) Set(height uint32) ([]utxo.Entry, uint32, error) { points := d.Checkpoints() if len(points) == 0 { return nil, 0, fmt.Errorf("service: no checkpoints in %s", strings.Join(d.Dirs, ",")) } at := points[0] for _, p := range points { if p <= height { at = p } } d.mu.Lock() defer d.mu.Unlock() if d.have && d.cached == at { return d.set, at, nil } path, ok := d.file(at) if !ok { return nil, at, fmt.Errorf("service: no set file at %d", at) } raw, err := os.ReadFile(path) if err != nil { return nil, at, err } entries := make([]utxo.Entry, 0, len(raw)/utxostore.EntrySize) buf := make([]byte, utxostore.EntrySize) for i := 0; i+utxostore.EntrySize <= len(raw); i += utxostore.EntrySize { copy(buf, raw[i:i+utxostore.EntrySize]) entries = append(entries, utxo.Decode(buf)) } d.set, d.cached, d.have = entries, at, true return entries, at, nil } // UTXOQuery is the POST body of the utxo query. type UTXOQuery struct { Outpoints []string `json:"outpoints"` // Height is the height the question is asked at; null or absent is the // tip of the checkpoint chain. Height *uint32 `json:"height"` } // UTXOAnswer is one outpoint's answer. type UTXOAnswer struct { OutPoint string `json:"outpoint"` // Unspent is whether the checkpoint's set holds it. Unspent bool `json:"unspent"` // Value and Height are the entry's own, when it is unspent. Value int64 `json:"value,omitempty"` Height uint32 `json:"created_height,omitempty"` // Coinbase is set for a coinbase output. Coinbase bool `json:"coinbase,omitempty"` // AnsweredAt is the checkpoint the answer comes from. A query above the // last checkpoint is answered at it, and the caller can see which. AnsweredAt uint32 `json:"answered_at"` } // UTXOResponse is the answer to a query. type UTXOResponse struct { Chain string `json:"chain"` Asked *uint32 `json:"asked_height,omitempty"` At uint32 `json:"answered_at"` Results []UTXOAnswer `json:"results"` } // routesUTXO registers the query endpoint on a mux, one chain per source. func routesUTXO(mux *http.ServeMux, srcs map[string]UTXOSource) { names := make([]string, 0, len(srcs)) for name := range srcs { names = append(names, name) } sort.Strings(names) mux.HandleFunc("POST /v1/chains/{chain}/utxo/query", func(w http.ResponseWriter, r *http.Request) { chainName := r.PathValue("chain") src, ok := srcs[chainName] if !ok { writeErr(w, http.StatusNotFound, fmt.Sprintf("this instance holds no UTXO data for %q; it has %s", chainName, strings.Join(names, ","))) return } var q UTXOQuery if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<20)).Decode(&q); err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } if len(q.Outpoints) == 0 { writeErr(w, http.StatusBadRequest, "no outpoints") return } height := ^uint32(0) if q.Height != nil { height = *q.Height } set, at, err := src.Set(height) if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } resp := UTXOResponse{Chain: chainName, Asked: q.Height, At: at} for _, op := range q.Outpoints { want, err := parseOutPoint(op) if err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } e, ok := findEntry(set, want) ans := UTXOAnswer{OutPoint: op, Unspent: ok, AnsweredAt: at} if ok { ans.Value, ans.Height, ans.Coinbase = e.Value, e.Height, e.Coinbase } resp.Results = append(resp.Results, ans) } writeJSON(w, resp) }) mux.HandleFunc("GET /v1/chains/{chain}/utxo/checkpoints", func(w http.ResponseWriter, r *http.Request) { chainName := r.PathValue("chain") src, ok := srcs[chainName] if !ok { writeErr(w, http.StatusNotFound, fmt.Sprintf("this instance holds no UTXO data for %q; it has %s", chainName, strings.Join(names, ","))) return } writeJSON(w, map[string]any{"chain": chainName, "checkpoints": src.Checkpoints()}) }) } // writeErr answers with a status and a reason. func writeErr(w http.ResponseWriter, code int, msg string) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) _ = json.NewEncoder(w).Encode(map[string]string{"error": msg}) } // parseOutPoint reads a txid:vout the way the protocol prints it. func parseOutPoint(s string) (wire.OutPoint, error) { i := strings.LastIndexByte(s, ':') if i <= 0 { return wire.OutPoint{}, fmt.Errorf("an outpoint is txid:vout") } h, err := chainhash.NewHashFromStr(s[:i]) if err != nil { return wire.OutPoint{}, fmt.Errorf("%q is not txid:vout", s) } v, err := strconv.ParseUint(s[i+1:], 10, 32) if err != nil { return wire.OutPoint{}, fmt.Errorf("%q is not txid:vout", s) } return wire.OutPoint{Hash: *h, Index: uint32(v)}, nil } // findEntry is a binary search over the entries' sort order. func findEntry(set []utxo.Entry, op wire.OutPoint) (utxo.Entry, bool) { i := sort.Search(len(set), func(i int) bool { return !utxo.LessEntry(set[i], utxo.Entry{OutPoint: op}) }) if i < len(set) && set[i].OutPoint == op { return set[i], true } return utxo.Entry{}, false }