// Package utxoserve serves one chain's UTXO dataset: the canonical sets at the // chain's retarget heights and the per-block diffs that reach everything // between them. // // The artifacts are the builder's, unchanged: a set at a height is a file of // fixed-width entries sorted by outpoint, and a diff is the touches of exactly // one block. A client that holds a snapshot and applies the diffs after it // reaches every height in the epoch and recomputes the next snapshot's name, // which is the check: it never has to trust a server for a set, and a diff that // is wrong gives a different name at the next boundary. // // The paths are chain-scoped because the dataset is: one process holds a UTXO // dataset per chain, and the shared prefix's snapshots and diffs are written // once and read by both. package utxoserve import ( "encoding/binary" "encoding/json" "errors" "fmt" "net/http" "os" "path/filepath" "sort" "strconv" "strings" "git.smesh.lol/nostrino/pkg/crypto/chainhash" utxostore "git.smesh.lol/btcd-lite/internal/utxo/store" ) // Chain is one chain's UTXO dataset: where its snapshots and diffs are, and the // cadence that says which heights are snapshots. // // Sets and Diffs are lists because a two-chain instance stores the shared // prefix's artifacts once: a height below the fork is looked for in the shared // directory first and in the chain's own second. type Chain struct { // Name is the chain the paths are scoped to: "btc" or "xbt". Name string // Sets are the directories that hold set-.dat, in lookup order. Sets []string // Diffs are the directories that hold diff--.dat, in lookup // order. Diffs []string // Interval is the snapshot cadence: the chain's retarget interval. Interval uint32 } // Index is a chain's snapshots, indexed by height. type Index struct { chain Chain points []uint32 names map[uint32]chainhash.Hash files map[uint32]string } // Points is the snapshot heights, ascending. func (i *Index) Points() []uint32 { return append([]uint32(nil), i.points...) } // Interval is the cadence the dataset was built at. func (i *Index) Interval() uint32 { return i.chain.Interval } // Name is the name of the set at a height, when it is a snapshot height. func (i *Index) Name(height uint32) (chainhash.Hash, bool) { n, ok := i.names[height] return n, ok } // NearestAtOrBelow is the snapshot height a client should start from to reach // height. func (i *Index) NearestAtOrBelow(height uint32) (uint32, bool) { var best uint32 found := false for _, p := range i.points { if p <= height { best, found = p, true continue } break } return best, found } // Open indexes a chain's dataset: every snapshot file, named by its bytes. func Open(c Chain) (*Index, error) { if c.Name == "" || len(c.Sets) == 0 { return nil, fmt.Errorf("utxoserve: a chain name and at least one set directory are required") } idx := &Index{chain: c, names: map[uint32]chainhash.Hash{}, files: map[uint32]string{}} seen := map[uint32]bool{} for _, dir := range c.Sets { names, err := utxostore.Names(dir) if err != nil { if os.IsNotExist(errors.Unwrap(err)) { continue } return nil, fmt.Errorf("utxoserve: %s: %w", dir, err) } for h, n := range names { if seen[h] { continue } path := filepath.Join(dir, utxostore.SetFile(h)) if _, err := os.Stat(path); err != nil { return nil, fmt.Errorf("utxoserve: %s names %d and the file is not there", dir, h) } seen[h] = true idx.points = append(idx.points, h) idx.files[h] = path idx.names[h] = n } } if len(idx.points) == 0 { return nil, fmt.Errorf("utxoserve: %s has no snapshots in %s", c.Name, strings.Join(c.Sets, ",")) } sort.Slice(idx.points, func(i, j int) bool { return idx.points[i] < idx.points[j] }) return idx, nil } // diffPath is the file holding the touches of block h: the step from the set at // h-1 to the set at h. func diffPath(dirs []string, h uint32) (string, bool) { if h == 0 { return "", false } name := utxostore.DiffFile(h-1, h) for _, dir := range dirs { path := filepath.Join(dir, name) if _, err := os.Stat(path); err == nil { return path, true } } return "", false } // Manifest is what a client reads first: the cadence, the snapshots with the // name of each set, and the heights a diff run covers. type Manifest struct { Chain string `json:"chain"` Base uint32 `json:"base"` Tip uint32 `json:"tip"` Interval uint32 `json:"interval"` // Snapshot is every snapshot height, ascending, with the name of its set. Snapshots []Snapshot `json:"snapshots"` } // Snapshot is one boundary. type Snapshot struct { Height uint32 `json:"height"` Name string `json:"name"` } // Routes registers the chain's endpoints on a mux. func Routes(mux *http.ServeMux, c Chain) { prefix := "/v1/utxo/" + c.Name mux.HandleFunc("GET "+prefix+"/manifest", func(w http.ResponseWriter, r *http.Request) { idx, err := Open(c) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } m := Manifest{Chain: c.Name, Base: idx.points[0], Tip: idx.points[len(idx.points)-1], Interval: c.Interval} for _, h := range idx.points { m.Snapshots = append(m.Snapshots, Snapshot{Height: h, Name: idx.names[h].String()}) } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(m) }) // One snapshot, by height. A height that is not a snapshot is not answered // with the nearest one: a client that asked for 100 and got 0 would have to // discover the difference itself, so the answer says which height it does // hold. mux.HandleFunc("GET "+prefix+"/snapshot/{height}", func(w http.ResponseWriter, r *http.Request) { idx, err := Open(c) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } h64, err := strconv.ParseUint(r.PathValue("height"), 10, 32) if err != nil { http.Error(w, "height is not a number", http.StatusBadRequest) return } h := uint32(h64) n, ok := idx.names[h] if !ok { near, found := idx.NearestAtOrBelow(h) if !found { http.Error(w, fmt.Sprintf("no snapshot at or below %d", h), http.StatusNotFound) return } http.Error(w, fmt.Sprintf("%d is not a snapshot height; the nearest at or below is %d", h, near), http.StatusNotFound) return } raw, err := os.ReadFile(idx.files[h]) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if got := chainhash.DoubleHashH(raw); got != n { http.Error(w, "the set file no longer hashes to the name the manifest gives it", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("ETag", `"`+n.String()+`"`) w.Header().Set("X-Set-Name", n.String()) w.Header().Set("X-Snapshot-Height", strconv.FormatUint(uint64(h), 10)) _, _ = w.Write(raw) }) // A run of per-block diffs, as length-prefixed records. A run that crosses // a snapshot is refused: the client has to start from that snapshot, or it // would be applying a diff to a set the server never served. mux.HandleFunc("GET "+prefix+"/diffs/{range}", func(w http.ResponseWriter, r *http.Request) { from, to, err := parseRange(r.PathValue("range")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if from == 0 { http.Error(w, "block 0 has no diff: its effects are in the snapshot at 0", http.StatusBadRequest) return } for h := from; h < to; h++ { if c.Interval > 0 && h%c.Interval == 0 && h != to-1 { http.Error(w, fmt.Sprintf("the run crosses the snapshot at %d; end there or start after it", h), http.StatusBadRequest) return } } // Every file is checked before the first is written, so a run with a // hole in it is refused rather than half-served. paths := make([]string, 0, to-from) for h := from; h < to; h++ { path, ok := diffPath(c.Diffs, h) if !ok { http.Error(w, fmt.Sprintf("no diff at %d", h), http.StatusNotFound) return } paths = append(paths, path) } w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("X-Diff-From", strconv.FormatUint(uint64(from), 10)) w.Header().Set("X-Diff-To", strconv.FormatUint(uint64(to), 10)) var pfx [4]byte for _, path := range paths { raw, err := os.ReadFile(path) if err != nil { return } binary.LittleEndian.PutUint32(pfx[:], uint32(len(raw))) if _, err := w.Write(pfx[:]); err != nil { return } if _, err := w.Write(raw); err != nil { return } } }) } 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("%q is not from-to", seg) } if b <= a { return 0, 0, fmt.Errorf("%q is empty", seg) } return a, b, nil }