serve_test.go raw

   1  package utxoserve_test
   2  
   3  import (
   4  	"encoding/binary"
   5  	"encoding/json"
   6  	"io"
   7  	"net/http"
   8  	"net/http/httptest"
   9  	"os"
  10  	"path/filepath"
  11  	"testing"
  12  
  13  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  14  
  15  	"git.smesh.lol/btcd-lite/internal/fetch"
  16  	"git.smesh.lol/btcd-lite/internal/utxo"
  17  	utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve"
  18  	utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
  19  	"git.smesh.lol/btcd-lite/internal/wire"
  20  )
  21  
  22  // op is a distinct outpoint per index.
  23  func op(i uint32) wire.OutPoint {
  24  	var h [32]byte
  25  	binary.LittleEndian.PutUint32(h[:4], i)
  26  	binary.BigEndian.PutUint32(h[28:], i)
  27  	return wire.OutPoint{Hash: h}
  28  }
  29  
  30  // fixture builds a twenty-height chain with a snapshot every ten: snapshots at
  31  // 0, 10 and 20, and a diff for every block. It returns the chain the service is
  32  // configured with and the name of each snapshot's set.
  33  func fixture(t *testing.T) (utxoserve.Chain, map[uint32]chainhash.Hash) {
  34  	t.Helper()
  35  	dir := t.TempDir()
  36  	sets := filepath.Join(dir, "sets")
  37  	diffs := filepath.Join(dir, "diffs")
  38  	c := utxoserve.Chain{Name: "btc", Sets: []string{sets}, Diffs: []string{diffs}, Interval: 10}
  39  	names := map[uint32]chainhash.Hash{}
  40  	var set []utxo.Entry
  41  	write := func(h uint32) {
  42  		n, err := utxostore.WriteSetFile(sets, h, set)
  43  		if err != nil {
  44  			t.Fatal(err)
  45  		}
  46  		names[h] = n
  47  	}
  48  	// touches is what one block did: five outputs, nothing spent.
  49  	touches := func(h uint32) []utxo.Touch {
  50  		var ts []utxo.Touch
  51  		for k := uint32(0); k < 5; k++ {
  52  			i := h*5 + k
  53  			ts = append(ts, utxo.Touch{OutPoint: op(i), Height: h,
  54  				New: utxo.Entry{OutPoint: op(i), Value: int64(i) + 1, Height: h}})
  55  		}
  56  		return ts
  57  	}
  58  	// The snapshot at a height is the set after that block, so block 0's
  59  	// effects are in the base and every later block has its own diff.
  60  	var err error
  61  	if set, err = utxo.ApplyRange(set, touches(0)); err != nil {
  62  		t.Fatal(err)
  63  	}
  64  	write(0)
  65  	for h := uint32(1); h <= 20; h++ {
  66  		ts := touches(h)
  67  		if set, err = utxo.ApplyRange(set, ts); err != nil {
  68  			t.Fatal(err)
  69  		}
  70  		if _, err := utxostore.CutRange(diffs, h-1, h, ts); err != nil {
  71  			t.Fatal(err)
  72  		}
  73  		if h%10 == 0 {
  74  			write(h)
  75  		}
  76  	}
  77  	return c, names
  78  }
  79  
  80  // handler mounts the chain's routes on a fresh mux, which is what a command
  81  // does with its own.
  82  func handler(c utxoserve.Chain) http.Handler {
  83  	mux := http.NewServeMux()
  84  	utxoserve.Routes(mux, c)
  85  	return mux
  86  }
  87  
  88  // TestManifestNamesEverySnapshot: the manifest lists the retarget heights and
  89  // the name of each set.
  90  func TestManifestNamesEverySnapshot(t *testing.T) {
  91  	c, names := fixture(t)
  92  	srv := httptest.NewServer(handler(c))
  93  	defer srv.Close()
  94  	var m utxoserve.Manifest
  95  	getJSON(t, srv.URL+"/v1/utxo/btc/manifest", &m)
  96  	if m.Base != 0 || m.Tip != 20 || m.Interval != 10 {
  97  		t.Fatalf("manifest %+v", m)
  98  	}
  99  	if len(m.Snapshots) != 3 {
 100  		t.Fatalf("%d snapshots", len(m.Snapshots))
 101  	}
 102  	for i, h := range []uint32{0, 10, 20} {
 103  		if m.Snapshots[i].Height != h || m.Snapshots[i].Name != names[h].String() {
 104  			t.Fatalf("snapshot %d is %+v, want height %d name %s", i, m.Snapshots[i], h, names[h])
 105  		}
 106  	}
 107  }
 108  
 109  // TestSnapshotServed: a snapshot height is served with its name, and a height
 110  // between two of them is refused with the one below it named.
 111  func TestSnapshotServed(t *testing.T) {
 112  	c, names := fixture(t)
 113  	srv := httptest.NewServer(handler(c))
 114  	defer srv.Close()
 115  	raw := get(t, srv.URL+"/v1/utxo/btc/snapshot/10")
 116  	if len(raw)%utxostore.EntrySize != 0 {
 117  		t.Fatalf("the snapshot is %d bytes", len(raw))
 118  	}
 119  	if got := chainhash.DoubleHashH(raw); got != names[10] {
 120  		t.Fatalf("the served set hashes to %s, the manifest says %s", got, names[10])
 121  	}
 122  	resp, err := http.Get(srv.URL + "/v1/utxo/btc/snapshot/5")
 123  	if err != nil {
 124  		t.Fatal(err)
 125  	}
 126  	body, _ := io.ReadAll(resp.Body)
 127  	resp.Body.Close()
 128  	if resp.StatusCode != http.StatusNotFound {
 129  		t.Fatalf("a snapshot was served at a height that has none: %d", resp.StatusCode)
 130  	}
 131  	if !contains(string(body), "0") {
 132  		t.Fatalf("the refusal does not name the snapshot below: %s", body)
 133  	}
 134  }
 135  
 136  // TestDiffRun: a run of per-block diffs, applied to the snapshot below it,
 137  // reproduces the next snapshot's name.
 138  func TestDiffRun(t *testing.T) {
 139  	c, names := fixture(t)
 140  	srv := httptest.NewServer(handler(c))
 141  	defer srv.Close()
 142  	run := get(t, srv.URL+"/v1/utxo/btc/diffs/1-11")
 143  	base := get(t, srv.URL+"/v1/utxo/btc/snapshot/0")
 144  	set := decode(base)
 145  	at := 0
 146  	count := 0
 147  	for at < len(run) {
 148  		n := int(binary.LittleEndian.Uint32(run[at:]))
 149  		d, err := utxo.DecodeDiff(run[at+4 : at+4+n])
 150  		if err != nil {
 151  			t.Fatal(err)
 152  		}
 153  		at += 4 + n
 154  		if set, err = d.ApplyTo(set); err != nil {
 155  			t.Fatal(err)
 156  		}
 157  		count++
 158  	}
 159  	if count != 10 {
 160  		t.Fatalf("%d diffs for heights 1..10", count)
 161  	}
 162  	if got := utxostore.NameOf(set); got != names[10] {
 163  		t.Fatalf("applying the run gives %s, the snapshot at 10 is %s", got, names[10])
 164  	}
 165  	// A run that crosses a snapshot is refused: 10 is inside it.
 166  	resp, err := http.Get(srv.URL + "/v1/utxo/btc/diffs/5-15")
 167  	if err != nil {
 168  		t.Fatal(err)
 169  	}
 170  	defer resp.Body.Close()
 171  	if resp.StatusCode != http.StatusBadRequest {
 172  		t.Fatalf("a run across a snapshot answered %d", resp.StatusCode)
 173  	}
 174  }
 175  
 176  // TestUTXOFetchE2E: a client fetches the chain and reaches every snapshot, and
 177  // each name it computes is the one the manifest published.
 178  func TestUTXOFetchE2E(t *testing.T) {
 179  	c, names := fixture(t)
 180  	srv := httptest.NewServer(handler(c))
 181  	defer srv.Close()
 182  	dst := t.TempDir()
 183  	cl := &fetch.Client{Base: srv.URL}
 184  	n, err := cl.UTXO(t.Context(), "btc", dst)
 185  	if err != nil {
 186  		t.Fatalf("fetch: %v", err)
 187  	}
 188  	if n != len(names) {
 189  		t.Fatalf("reached %d of %d snapshots", n, len(names))
 190  	}
 191  	for h, want := range names {
 192  		got, err := utxostore.SetName(dst, h)
 193  		if err != nil {
 194  			t.Fatalf("height %d: %v", h, err)
 195  		}
 196  		if got != want {
 197  			t.Fatalf("height %d names %s, the chain holds %s", h, got, want)
 198  		}
 199  	}
 200  }
 201  
 202  // TestWrongDiffRefused: a service that hands over a diff whose result is not
 203  // the name it published is stopped at that boundary.
 204  func TestWrongDiffRefused(t *testing.T) {
 205  	c, names := fixture(t)
 206  	src := httptest.NewServer(handler(c))
 207  	defer src.Close()
 208  	// A proxy that corrupts the first diff's bytes.
 209  	proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 210  		resp, err := http.Get(src.URL + r.URL.Path)
 211  		if err != nil {
 212  			http.Error(w, err.Error(), 502)
 213  			return
 214  		}
 215  		defer resp.Body.Close()
 216  		body, _ := io.ReadAll(resp.Body)
 217  		if r.URL.Path == "/v1/utxo/btc/diffs/1-11" && len(body) > 4 {
 218  			// A byte of one entry, so the applied set differs from the one
 219  			// the chain holds and the name at the next snapshot catches it.
 220  			body[len(body)-1] ^= 0xff
 221  		}
 222  		w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
 223  		_, _ = w.Write(body)
 224  	}))
 225  	defer proxy.Close()
 226  	dst := t.TempDir()
 227  	cl := &fetch.Client{Base: proxy.URL}
 228  	if _, err := cl.UTXO(t.Context(), "btc", dst); err == nil {
 229  		t.Fatal("a corrupt diff was applied")
 230  	}
 231  	// The base the client received is still the chain's.
 232  	if got, err := utxostore.SetName(dst, 0); err != nil || got != names[0] {
 233  		t.Fatalf("base %v %v", got, err)
 234  	}
 235  }
 236  
 237  func get(t *testing.T, u string) []byte {
 238  	t.Helper()
 239  	resp, err := http.Get(u)
 240  	if err != nil {
 241  		t.Fatal(err)
 242  	}
 243  	defer resp.Body.Close()
 244  	body, err := io.ReadAll(resp.Body)
 245  	if err != nil {
 246  		t.Fatal(err)
 247  	}
 248  	if resp.StatusCode != http.StatusOK {
 249  		t.Fatalf("%s: %d %s", u, resp.StatusCode, body)
 250  	}
 251  	return body
 252  }
 253  
 254  func getJSON(t *testing.T, u string, v any) {
 255  	t.Helper()
 256  	body := get(t, u)
 257  	if err := json.Unmarshal(body, v); err != nil {
 258  		t.Fatal(err)
 259  	}
 260  }
 261  
 262  func decode(raw []byte) []utxo.Entry {
 263  	out := make([]utxo.Entry, 0, len(raw)/utxostore.EntrySize)
 264  	buf := make([]byte, utxostore.EntrySize)
 265  	for i := 0; i+utxostore.EntrySize <= len(raw); i += utxostore.EntrySize {
 266  		copy(buf, raw[i:i+utxostore.EntrySize])
 267  		out = append(out, utxo.Decode(buf))
 268  	}
 269  	return out
 270  }
 271  
 272  func contains(s, sub string) bool {
 273  	for i := 0; i+len(sub) <= len(s); i++ {
 274  		if s[i:i+len(sub)] == sub {
 275  			return true
 276  		}
 277  	}
 278  	return false
 279  }
 280  
 281  // TestManifestReadsTheIndex: the manifest's names come from the index the
 282  // builder wrote, not from reading every snapshot back, so answering it costs one
 283  // small file however large the dataset is. A set file edited behind the index is
 284  // still refused when it is served.
 285  func TestManifestReadsTheIndex(t *testing.T) {
 286  	c, names := fixture(t)
 287  	// Overwrite a set with bytes that hash to something else, keeping its
 288  	// length, and leave the index alone.
 289  	path := filepath.Join(c.Sets[0], utxostore.SetFile(10))
 290  	raw, err := os.ReadFile(path)
 291  	if err != nil {
 292  		t.Fatal(err)
 293  	}
 294  	raw[0] ^= 0xff
 295  	if err := os.WriteFile(path, raw, 0o644); err != nil {
 296  		t.Fatal(err)
 297  	}
 298  	srv := httptest.NewServer(handler(c))
 299  	defer srv.Close()
 300  	var m utxoserve.Manifest
 301  	getJSON(t, srv.URL+"/v1/utxo/btc/manifest", &m)
 302  	for _, s := range m.Snapshots {
 303  		if s.Height == 10 && s.Name != names[10].String() {
 304  			t.Fatalf("the manifest names %s for height 10, the index says %s", s.Name, names[10])
 305  		}
 306  	}
 307  	// Serving it catches the edit.
 308  	resp, err := http.Get(srv.URL + "/v1/utxo/btc/snapshot/10")
 309  	if err != nil {
 310  		t.Fatal(err)
 311  	}
 312  	defer resp.Body.Close()
 313  	if resp.StatusCode == http.StatusOK {
 314  		t.Fatal("a set file edited behind the index was served")
 315  	}
 316  }
 317