serve.go raw

   1  // Package utxoserve serves one chain's UTXO dataset: the canonical sets at the
   2  // chain's retarget heights and the per-block diffs that reach everything
   3  // between them.
   4  //
   5  // The artifacts are the builder's, unchanged: a set at a height is a file of
   6  // fixed-width entries sorted by outpoint, and a diff is the touches of exactly
   7  // one block. A client that holds a snapshot and applies the diffs after it
   8  // reaches every height in the epoch and recomputes the next snapshot's name,
   9  // which is the check: it never has to trust a server for a set, and a diff that
  10  // is wrong gives a different name at the next boundary.
  11  //
  12  // The paths are chain-scoped because the dataset is: one process holds a UTXO
  13  // dataset per chain, and the shared prefix's snapshots and diffs are written
  14  // once and read by both.
  15  package utxoserve
  16  
  17  import (
  18  	"encoding/binary"
  19  	"encoding/json"
  20  	"errors"
  21  	"fmt"
  22  	"net/http"
  23  	"os"
  24  	"path/filepath"
  25  	"sort"
  26  	"strconv"
  27  	"strings"
  28  
  29  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  30  
  31  	utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
  32  )
  33  
  34  // Chain is one chain's UTXO dataset: where its snapshots and diffs are, and the
  35  // cadence that says which heights are snapshots.
  36  //
  37  // Sets and Diffs are lists because a two-chain instance stores the shared
  38  // prefix's artifacts once: a height below the fork is looked for in the shared
  39  // directory first and in the chain's own second.
  40  type Chain struct {
  41  	// Name is the chain the paths are scoped to: "btc" or "xbt".
  42  	Name string
  43  	// Sets are the directories that hold set-<height>.dat, in lookup order.
  44  	Sets []string
  45  	// Diffs are the directories that hold diff-<from>-<to>.dat, in lookup
  46  	// order.
  47  	Diffs []string
  48  	// Interval is the snapshot cadence: the chain's retarget interval.
  49  	Interval uint32
  50  }
  51  
  52  // Index is a chain's snapshots, indexed by height.
  53  type Index struct {
  54  	chain  Chain
  55  	points []uint32
  56  	names  map[uint32]chainhash.Hash
  57  	files  map[uint32]string
  58  }
  59  
  60  // Points is the snapshot heights, ascending.
  61  func (i *Index) Points() []uint32 { return append([]uint32(nil), i.points...) }
  62  
  63  // Interval is the cadence the dataset was built at.
  64  func (i *Index) Interval() uint32 { return i.chain.Interval }
  65  
  66  // Name is the name of the set at a height, when it is a snapshot height.
  67  func (i *Index) Name(height uint32) (chainhash.Hash, bool) {
  68  	n, ok := i.names[height]
  69  	return n, ok
  70  }
  71  
  72  // NearestAtOrBelow is the snapshot height a client should start from to reach
  73  // height.
  74  func (i *Index) NearestAtOrBelow(height uint32) (uint32, bool) {
  75  	var best uint32
  76  	found := false
  77  	for _, p := range i.points {
  78  		if p <= height {
  79  			best, found = p, true
  80  			continue
  81  		}
  82  		break
  83  	}
  84  	return best, found
  85  }
  86  
  87  // Open indexes a chain's dataset: every snapshot file, named by its bytes.
  88  func Open(c Chain) (*Index, error) {
  89  	if c.Name == "" || len(c.Sets) == 0 {
  90  		return nil, fmt.Errorf("utxoserve: a chain name and at least one set directory are required")
  91  	}
  92  	idx := &Index{chain: c, names: map[uint32]chainhash.Hash{}, files: map[uint32]string{}}
  93  	seen := map[uint32]bool{}
  94  	for _, dir := range c.Sets {
  95  		names, err := utxostore.Names(dir)
  96  		if err != nil {
  97  			if os.IsNotExist(errors.Unwrap(err)) {
  98  				continue
  99  			}
 100  			return nil, fmt.Errorf("utxoserve: %s: %w", dir, err)
 101  		}
 102  		for h, n := range names {
 103  			if seen[h] {
 104  				continue
 105  			}
 106  			path := filepath.Join(dir, utxostore.SetFile(h))
 107  			if _, err := os.Stat(path); err != nil {
 108  				return nil, fmt.Errorf("utxoserve: %s names %d and the file is not there", dir, h)
 109  			}
 110  			seen[h] = true
 111  			idx.points = append(idx.points, h)
 112  			idx.files[h] = path
 113  			idx.names[h] = n
 114  		}
 115  	}
 116  	if len(idx.points) == 0 {
 117  		return nil, fmt.Errorf("utxoserve: %s has no snapshots in %s", c.Name, strings.Join(c.Sets, ","))
 118  	}
 119  	sort.Slice(idx.points, func(i, j int) bool { return idx.points[i] < idx.points[j] })
 120  	return idx, nil
 121  }
 122  
 123  // diffPath is the file holding the touches of block h: the step from the set at
 124  // h-1 to the set at h.
 125  func diffPath(dirs []string, h uint32) (string, bool) {
 126  	if h == 0 {
 127  		return "", false
 128  	}
 129  	name := utxostore.DiffFile(h-1, h)
 130  	for _, dir := range dirs {
 131  		path := filepath.Join(dir, name)
 132  		if _, err := os.Stat(path); err == nil {
 133  			return path, true
 134  		}
 135  	}
 136  	return "", false
 137  }
 138  
 139  // Manifest is what a client reads first: the cadence, the snapshots with the
 140  // name of each set, and the heights a diff run covers.
 141  type Manifest struct {
 142  	Chain    string `json:"chain"`
 143  	Base     uint32 `json:"base"`
 144  	Tip      uint32 `json:"tip"`
 145  	Interval uint32 `json:"interval"`
 146  	// Snapshot is every snapshot height, ascending, with the name of its set.
 147  	Snapshots []Snapshot `json:"snapshots"`
 148  }
 149  
 150  // Snapshot is one boundary.
 151  type Snapshot struct {
 152  	Height uint32 `json:"height"`
 153  	Name   string `json:"name"`
 154  }
 155  
 156  // Routes registers the chain's endpoints on a mux.
 157  func Routes(mux *http.ServeMux, c Chain) {
 158  	prefix := "/v1/utxo/" + c.Name
 159  	mux.HandleFunc("GET "+prefix+"/manifest", func(w http.ResponseWriter, r *http.Request) {
 160  		idx, err := Open(c)
 161  		if err != nil {
 162  			http.Error(w, err.Error(), http.StatusNotFound)
 163  			return
 164  		}
 165  		m := Manifest{Chain: c.Name, Base: idx.points[0], Tip: idx.points[len(idx.points)-1], Interval: c.Interval}
 166  		for _, h := range idx.points {
 167  			m.Snapshots = append(m.Snapshots, Snapshot{Height: h, Name: idx.names[h].String()})
 168  		}
 169  		w.Header().Set("Content-Type", "application/json")
 170  		_ = json.NewEncoder(w).Encode(m)
 171  	})
 172  	// One snapshot, by height. A height that is not a snapshot is not answered
 173  	// with the nearest one: a client that asked for 100 and got 0 would have to
 174  	// discover the difference itself, so the answer says which height it does
 175  	// hold.
 176  	mux.HandleFunc("GET "+prefix+"/snapshot/{height}", func(w http.ResponseWriter, r *http.Request) {
 177  		idx, err := Open(c)
 178  		if err != nil {
 179  			http.Error(w, err.Error(), http.StatusNotFound)
 180  			return
 181  		}
 182  		h64, err := strconv.ParseUint(r.PathValue("height"), 10, 32)
 183  		if err != nil {
 184  			http.Error(w, "height is not a number", http.StatusBadRequest)
 185  			return
 186  		}
 187  		h := uint32(h64)
 188  		n, ok := idx.names[h]
 189  		if !ok {
 190  			near, found := idx.NearestAtOrBelow(h)
 191  			if !found {
 192  				http.Error(w, fmt.Sprintf("no snapshot at or below %d", h), http.StatusNotFound)
 193  				return
 194  			}
 195  			http.Error(w, fmt.Sprintf("%d is not a snapshot height; the nearest at or below is %d", h, near), http.StatusNotFound)
 196  			return
 197  		}
 198  		raw, err := os.ReadFile(idx.files[h])
 199  		if err != nil {
 200  			http.Error(w, err.Error(), http.StatusInternalServerError)
 201  			return
 202  		}
 203  		if got := chainhash.DoubleHashH(raw); got != n {
 204  			http.Error(w, "the set file no longer hashes to the name the manifest gives it", http.StatusInternalServerError)
 205  			return
 206  		}
 207  		w.Header().Set("Content-Type", "application/octet-stream")
 208  		w.Header().Set("ETag", `"`+n.String()+`"`)
 209  		w.Header().Set("X-Set-Name", n.String())
 210  		w.Header().Set("X-Snapshot-Height", strconv.FormatUint(uint64(h), 10))
 211  		_, _ = w.Write(raw)
 212  	})
 213  	// A run of per-block diffs, as length-prefixed records. A run that crosses
 214  	// a snapshot is refused: the client has to start from that snapshot, or it
 215  	// would be applying a diff to a set the server never served.
 216  	mux.HandleFunc("GET "+prefix+"/diffs/{range}", func(w http.ResponseWriter, r *http.Request) {
 217  		from, to, err := parseRange(r.PathValue("range"))
 218  		if err != nil {
 219  			http.Error(w, err.Error(), http.StatusBadRequest)
 220  			return
 221  		}
 222  		if from == 0 {
 223  			http.Error(w, "block 0 has no diff: its effects are in the snapshot at 0", http.StatusBadRequest)
 224  			return
 225  		}
 226  		for h := from; h < to; h++ {
 227  			if c.Interval > 0 && h%c.Interval == 0 && h != to-1 {
 228  				http.Error(w, fmt.Sprintf("the run crosses the snapshot at %d; end there or start after it", h), http.StatusBadRequest)
 229  				return
 230  			}
 231  		}
 232  		// Every file is checked before the first is written, so a run with a
 233  		// hole in it is refused rather than half-served.
 234  		paths := make([]string, 0, to-from)
 235  		for h := from; h < to; h++ {
 236  			path, ok := diffPath(c.Diffs, h)
 237  			if !ok {
 238  				http.Error(w, fmt.Sprintf("no diff at %d", h), http.StatusNotFound)
 239  				return
 240  			}
 241  			paths = append(paths, path)
 242  		}
 243  		w.Header().Set("Content-Type", "application/octet-stream")
 244  		w.Header().Set("X-Diff-From", strconv.FormatUint(uint64(from), 10))
 245  		w.Header().Set("X-Diff-To", strconv.FormatUint(uint64(to), 10))
 246  		var pfx [4]byte
 247  		for _, path := range paths {
 248  			raw, err := os.ReadFile(path)
 249  			if err != nil {
 250  				return
 251  			}
 252  			binary.LittleEndian.PutUint32(pfx[:], uint32(len(raw)))
 253  			if _, err := w.Write(pfx[:]); err != nil {
 254  				return
 255  			}
 256  			if _, err := w.Write(raw); err != nil {
 257  				return
 258  			}
 259  		}
 260  	})
 261  }
 262  
 263  func parseRange(seg string) (uint32, uint32, error) {
 264  	var a, b uint32
 265  	if _, err := fmt.Sscanf(seg, "%d-%d", &a, &b); err != nil {
 266  		return 0, 0, fmt.Errorf("%q is not from-to", seg)
 267  	}
 268  	if b <= a {
 269  		return 0, 0, fmt.Errorf("%q is empty", seg)
 270  	}
 271  	return a, b, nil
 272  }
 273