serve_utxo_test.go raw
1 package gate
2
3 import (
4 "context"
5 "encoding/hex"
6 "encoding/json"
7 "net/http"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strconv"
12 "testing"
13 "time"
14
15 "git.smesh.lol/btcd-lite/internal/chains"
16 "git.smesh.lol/btcd-lite/internal/fetch"
17 utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
18 )
19
20 // TestServedUTXOChainFetches is the plan's API path end to end: an instance
21 // filled from a node, a checkpoint chain built over the blocks it stored, the
22 // chain published, and a client fetching it over HTTP and reaching every
23 // boundary with the name the source holds.
24 func TestServedUTXOChainFetches(t *testing.T) {
25 if _, err := exec.LookPath("go"); err != nil {
26 t.Skip("go is not on PATH")
27 }
28 r := nodeOn(t)
29 r.createWallet(t)
30 r.mine(t, 300)
31 tip, err := strconv.Atoi(r.must(t, "getblockcount"))
32 if err != nil {
33 t.Fatal(err)
34 }
35 bin := t.TempDir()
36 build := exec.Command("go", "build", "-o", filepath.Join(bin, "btcd-lited"), "./cmd/btcd-lited")
37 build.Dir = "../.."
38 if out, err := build.CombinedOutput(); err != nil {
39 t.Fatalf("build: %v\n%s", err, out)
40 }
41 data := t.TempDir()
42 instPort := freePort(t)
43 inst := startProcess(t, filepath.Join(bin, "btcd-lited"),
44 "-data", data, "-listen", "127.0.0.1:"+itoa(instPort),
45 "-chain", "btc", "-peer", "127.0.0.1:"+itoa(r.p2p), "-regtest")
46 waitForBlocks(t, inst, filepath.Join(data, "instance.log"), "http://127.0.0.1:"+itoa(instPort), tip+1)
47 t.Logf("the instance filled %d blocks", tip+1)
48 // The serve command builds the checkpoint chain over that store and
49 // publishes it beside the chunks: one command, one address.
50 serveBin := filepath.Join(bin, "btcd-lite-serve")
51 buildServe := exec.Command("go", "build", "-o", serveBin, "./cmd/btcd-lite-serve")
52 buildServe.Dir = "../.."
53 if out, err := buildServe.CombinedOutput(); err != nil {
54 t.Fatalf("build serve: %v\n%s", err, out)
55 }
56 port := freePort(t)
57 serveCmd := startProcess(t, serveBin,
58 "-data", data, "-listen", "127.0.0.1:"+itoa(port), "-regtest")
59 base := "http://127.0.0.1:" + itoa(port)
60 waitForHTTP(t, base+"/v1/utxo/btc/manifest")
61 // The dataset's snapshots are the shared prefix's, because the whole
62 // regtest chain is below the fork.
63 utxoDir := filepath.Join(data, "utxo", "canonical")
64 t.Cleanup(func() { _ = serveCmd })
65 var manifest json.RawMessage
66 get(t, base+"/v1/utxo/btc/manifest", &manifest)
67 t.Logf("manifest: %s", manifest)
68 dst := t.TempDir()
69 c := &fetch.Client{Base: base}
70 n, err := c.UTXO(context.Background(), "btc", dst)
71 if err != nil {
72 t.Fatalf("client fetch: %v", err)
73 }
74 if n == 0 {
75 t.Fatal("the client reached no checkpoints")
76 }
77 interval := chains.Regtest().Exported.Retarget
78 for h := uint32(0); h <= uint32(tip); h += interval {
79 got, gerr := utxostore.SetName(dst, h)
80 if gerr != nil {
81 src, _ := filepath.Glob(filepath.Join(utxoDir, "set-*.dat"))
82 dstList, _ := filepath.Glob(filepath.Join(dst, "set-*.dat"))
83 t.Fatalf("the client has no set at %d: %v (source %v, client %v)", h, gerr, src, dstList)
84 }
85 want, werr := utxostore.SetName(utxoDir, h)
86 if werr != nil {
87 t.Fatalf("the source has no set at %d: %v", h, werr)
88 }
89 if got != want {
90 t.Fatalf("height %d: the client computes %s, the source holds %s", h, got, want)
91 }
92 }
93 // The filters the same command built are served beside the sets, and the
94 // filter a range returns for a height is the node's filter for that block.
95 for h := uint32(0); h <= uint32(tip); h += interval {
96 hash := r.must(t, "getblockhash", itoa(int(h)))
97 var node struct {
98 Filter string `json:"filter"`
99 }
100 raw, err := r.cli("getblockfilter", hash)
101 if err != nil {
102 t.Fatalf("getblockfilter %d: %v", h, err)
103 }
104 if err := json.Unmarshal([]byte(raw), &node); err != nil {
105 t.Fatalf("height %d: %v", h, err)
106 }
107 want, err := hex.DecodeString(node.Filter)
108 if err != nil {
109 t.Fatal(err)
110 }
111 name := rangeNamesOf(t, base, "btc", "flt", h, h+1)
112 if len(name) != 1 {
113 t.Fatalf("height %d: %d filter chunks", h, len(name))
114 }
115 served := chunkAt(t, base, name[0])
116 // The chunk is a length-prefixed filter.
117 filterBytes := served[4:]
118 if string(filterBytes) != string(want) {
119 t.Fatalf("height %d: the served filter is not the node's", h)
120 }
121 }
122 t.Logf("the client reached %d checkpoints from %d blocks, every boundary matching, and the filters are the node's", n, tip+1)
123 }
124
125 // startProcess runs a command and kills it when the test ends.
126 func startProcess(t *testing.T, path string, args ...string) *exec.Cmd {
127 t.Helper()
128 cmd := exec.Command(path, args...)
129 logFile, err := os.Create(filepath.Join(t.TempDir(), "log"))
130 if err != nil {
131 t.Fatal(err)
132 }
133 cmd.Stdout, cmd.Stderr = logFile, logFile
134 if err := cmd.Start(); err != nil {
135 t.Fatal(err)
136 }
137 t.Cleanup(func() {
138 _ = cmd.Process.Kill()
139 _ = cmd.Wait()
140 logFile.Close()
141 })
142 return cmd
143 }
144
145 // startHTTP serves handler on addr until the test ends.
146 func startHTTP(t *testing.T, addr string, handler http.Handler) {
147 t.Helper()
148 srv := &http.Server{Addr: addr, Handler: handler}
149 ready := make(chan struct{})
150 var once bool
151 _ = once
152 go func() {
153 close(ready)
154 _ = srv.ListenAndServe()
155 }()
156 <-ready
157 t.Cleanup(func() { _ = srv.Close() })
158 }
159
160 // waitForHTTP waits until the address answers.
161 func waitForHTTP(t *testing.T, url string) {
162 t.Helper()
163 deadline := time.Now().Add(30 * time.Second)
164 for {
165 resp, err := http.Get(url)
166 if err == nil {
167 resp.Body.Close()
168 return
169 }
170 if time.Now().After(deadline) {
171 t.Fatalf("%s never answered: %v", url, err)
172 }
173 time.Sleep(100 * time.Millisecond)
174 }
175 }
176