package utxoserve_test import ( "encoding/binary" "encoding/json" "io" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/fetch" "git.smesh.lol/btcd-lite/internal/utxo" utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve" utxostore "git.smesh.lol/btcd-lite/internal/utxo/store" "git.smesh.lol/btcd-lite/internal/wire" ) // op is a distinct outpoint per index. func op(i uint32) wire.OutPoint { var h [32]byte binary.LittleEndian.PutUint32(h[:4], i) binary.BigEndian.PutUint32(h[28:], i) return wire.OutPoint{Hash: h} } // fixture builds a twenty-height chain with a snapshot every ten: snapshots at // 0, 10 and 20, and a diff for every block. It returns the chain the service is // configured with and the name of each snapshot's set. func fixture(t *testing.T) (utxoserve.Chain, map[uint32]chainhash.Hash) { t.Helper() dir := t.TempDir() sets := filepath.Join(dir, "sets") diffs := filepath.Join(dir, "diffs") c := utxoserve.Chain{Name: "btc", Sets: []string{sets}, Diffs: []string{diffs}, Interval: 10} names := map[uint32]chainhash.Hash{} var set []utxo.Entry write := func(h uint32) { n, err := utxostore.WriteSetFile(sets, h, set) if err != nil { t.Fatal(err) } names[h] = n } // touches is what one block did: five outputs, nothing spent. touches := func(h uint32) []utxo.Touch { var ts []utxo.Touch for k := uint32(0); k < 5; k++ { i := h*5 + k ts = append(ts, utxo.Touch{OutPoint: op(i), Height: h, New: utxo.Entry{OutPoint: op(i), Value: int64(i) + 1, Height: h}}) } return ts } // The snapshot at a height is the set after that block, so block 0's // effects are in the base and every later block has its own diff. var err error if set, err = utxo.ApplyRange(set, touches(0)); err != nil { t.Fatal(err) } write(0) for h := uint32(1); h <= 20; h++ { ts := touches(h) if set, err = utxo.ApplyRange(set, ts); err != nil { t.Fatal(err) } if _, err := utxostore.CutRange(diffs, h-1, h, ts); err != nil { t.Fatal(err) } if h%10 == 0 { write(h) } } return c, names } // handler mounts the chain's routes on a fresh mux, which is what a command // does with its own. func handler(c utxoserve.Chain) http.Handler { mux := http.NewServeMux() utxoserve.Routes(mux, c) return mux } // TestManifestNamesEverySnapshot: the manifest lists the retarget heights and // the name of each set. func TestManifestNamesEverySnapshot(t *testing.T) { c, names := fixture(t) srv := httptest.NewServer(handler(c)) defer srv.Close() var m utxoserve.Manifest getJSON(t, srv.URL+"/v1/utxo/btc/manifest", &m) if m.Base != 0 || m.Tip != 20 || m.Interval != 10 { t.Fatalf("manifest %+v", m) } if len(m.Snapshots) != 3 { t.Fatalf("%d snapshots", len(m.Snapshots)) } for i, h := range []uint32{0, 10, 20} { if m.Snapshots[i].Height != h || m.Snapshots[i].Name != names[h].String() { t.Fatalf("snapshot %d is %+v, want height %d name %s", i, m.Snapshots[i], h, names[h]) } } } // TestSnapshotServed: a snapshot height is served with its name, and a height // between two of them is refused with the one below it named. func TestSnapshotServed(t *testing.T) { c, names := fixture(t) srv := httptest.NewServer(handler(c)) defer srv.Close() raw := get(t, srv.URL+"/v1/utxo/btc/snapshot/10") if len(raw)%utxostore.EntrySize != 0 { t.Fatalf("the snapshot is %d bytes", len(raw)) } if got := chainhash.DoubleHashH(raw); got != names[10] { t.Fatalf("the served set hashes to %s, the manifest says %s", got, names[10]) } resp, err := http.Get(srv.URL + "/v1/utxo/btc/snapshot/5") if err != nil { t.Fatal(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() if resp.StatusCode != http.StatusNotFound { t.Fatalf("a snapshot was served at a height that has none: %d", resp.StatusCode) } if !contains(string(body), "0") { t.Fatalf("the refusal does not name the snapshot below: %s", body) } } // TestDiffRun: a run of per-block diffs, applied to the snapshot below it, // reproduces the next snapshot's name. func TestDiffRun(t *testing.T) { c, names := fixture(t) srv := httptest.NewServer(handler(c)) defer srv.Close() run := get(t, srv.URL+"/v1/utxo/btc/diffs/1-11") base := get(t, srv.URL+"/v1/utxo/btc/snapshot/0") set := decode(base) at := 0 count := 0 for at < len(run) { n := int(binary.LittleEndian.Uint32(run[at:])) d, err := utxo.DecodeDiff(run[at+4 : at+4+n]) if err != nil { t.Fatal(err) } at += 4 + n if set, err = d.ApplyTo(set); err != nil { t.Fatal(err) } count++ } if count != 10 { t.Fatalf("%d diffs for heights 1..10", count) } if got := utxostore.NameOf(set); got != names[10] { t.Fatalf("applying the run gives %s, the snapshot at 10 is %s", got, names[10]) } // A run that crosses a snapshot is refused: 10 is inside it. resp, err := http.Get(srv.URL + "/v1/utxo/btc/diffs/5-15") if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusBadRequest { t.Fatalf("a run across a snapshot answered %d", resp.StatusCode) } } // TestUTXOFetchE2E: a client fetches the chain and reaches every snapshot, and // each name it computes is the one the manifest published. func TestUTXOFetchE2E(t *testing.T) { c, names := fixture(t) srv := httptest.NewServer(handler(c)) defer srv.Close() dst := t.TempDir() cl := &fetch.Client{Base: srv.URL} n, err := cl.UTXO(t.Context(), "btc", dst) if err != nil { t.Fatalf("fetch: %v", err) } if n != len(names) { t.Fatalf("reached %d of %d snapshots", n, len(names)) } for h, want := range names { got, err := utxostore.SetName(dst, h) if err != nil { t.Fatalf("height %d: %v", h, err) } if got != want { t.Fatalf("height %d names %s, the chain holds %s", h, got, want) } } } // TestWrongDiffRefused: a service that hands over a diff whose result is not // the name it published is stopped at that boundary. func TestWrongDiffRefused(t *testing.T) { c, names := fixture(t) src := httptest.NewServer(handler(c)) defer src.Close() // A proxy that corrupts the first diff's bytes. proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { resp, err := http.Get(src.URL + r.URL.Path) if err != nil { http.Error(w, err.Error(), 502) return } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) if r.URL.Path == "/v1/utxo/btc/diffs/1-11" && len(body) > 4 { // A byte of one entry, so the applied set differs from the one // the chain holds and the name at the next snapshot catches it. body[len(body)-1] ^= 0xff } w.Header().Set("Content-Type", resp.Header.Get("Content-Type")) _, _ = w.Write(body) })) defer proxy.Close() dst := t.TempDir() cl := &fetch.Client{Base: proxy.URL} if _, err := cl.UTXO(t.Context(), "btc", dst); err == nil { t.Fatal("a corrupt diff was applied") } // The base the client received is still the chain's. if got, err := utxostore.SetName(dst, 0); err != nil || got != names[0] { t.Fatalf("base %v %v", got, err) } } func get(t *testing.T, u string) []byte { t.Helper() resp, err := http.Get(u) if err != nil { t.Fatal(err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } if resp.StatusCode != http.StatusOK { t.Fatalf("%s: %d %s", u, resp.StatusCode, body) } return body } func getJSON(t *testing.T, u string, v any) { t.Helper() body := get(t, u) if err := json.Unmarshal(body, v); err != nil { t.Fatal(err) } } func decode(raw []byte) []utxo.Entry { out := 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]) out = append(out, utxo.Decode(buf)) } return out } func contains(s, sub string) bool { for i := 0; i+len(sub) <= len(s); i++ { if s[i:i+len(sub)] == sub { return true } } return false } // TestManifestReadsTheIndex: the manifest's names come from the index the // builder wrote, not from reading every snapshot back, so answering it costs one // small file however large the dataset is. A set file edited behind the index is // still refused when it is served. func TestManifestReadsTheIndex(t *testing.T) { c, names := fixture(t) // Overwrite a set with bytes that hash to something else, keeping its // length, and leave the index alone. path := filepath.Join(c.Sets[0], utxostore.SetFile(10)) raw, err := os.ReadFile(path) if err != nil { t.Fatal(err) } raw[0] ^= 0xff if err := os.WriteFile(path, raw, 0o644); err != nil { t.Fatal(err) } srv := httptest.NewServer(handler(c)) defer srv.Close() var m utxoserve.Manifest getJSON(t, srv.URL+"/v1/utxo/btc/manifest", &m) for _, s := range m.Snapshots { if s.Height == 10 && s.Name != names[10].String() { t.Fatalf("the manifest names %s for height 10, the index says %s", s.Name, names[10]) } } // Serving it catches the edit. resp, err := http.Get(srv.URL + "/v1/utxo/btc/snapshot/10") if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { t.Fatal("a set file edited behind the index was served") } }