service_test.go raw
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "net/http"
9 "net/http/httptest"
10 "sync"
11 "testing"
12
13 "git.smesh.lol/nostrino/pkg/blockcache"
14 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
15 )
16
17 // stubBlocks is a node that holds whatever the test put in it and counts reads.
18 type stubBlocks struct {
19 mu sync.Mutex
20 calls int
21 raw map[string][]byte
22 }
23
24 func (s *stubBlocks) blockByHash(_ context.Context, hash chainhash.Hash) ([]byte, error) {
25 s.mu.Lock()
26 defer s.mu.Unlock()
27
28 s.calls++
29
30 raw, ok := s.raw[hash.String()]
31
32 if !ok {
33 return nil, fmt.Errorf("getblock %s: not found", hash.String())
34 }
35
36 return raw, nil
37 }
38
39 func (s *stubBlocks) count() int {
40 s.mu.Lock()
41 defer s.mu.Unlock()
42
43 return s.calls
44 }
45
46 // serviceFor builds a service over a stub node and a cache in a temporary directory.
47 func serviceFor(t *testing.T, node blockReader) (*blockService, http.Handler) {
48 t.Helper()
49
50 cache, err := blockcache.Open(blockcache.Config{Dir: t.TempDir(), MaxBytes: 1 << 20})
51
52 if err != nil {
53 t.Fatal(err)
54 }
55
56 t.Cleanup(func() { _ = cache.Close() })
57
58 service := newBlockService("btc", node, cache, func(string, ...any) {})
59
60 return service, service.handler()
61 }
62
63 // TestTheFirstRequestFetchesAndTheSecondIsACacheHit: the node is read once, and the block the
64 // first client paid for is what the next one gets.
65 func TestTheFirstRequestFetchesAndTheSecondIsACacheHit(t *testing.T) {
66 hash := chainhash.HashH([]byte("block"))
67 node := &stubBlocks{raw: map[string][]byte{hash.String(): bytes.Repeat([]byte{7}, 128)}}
68
69 _, handler := serviceFor(t, node)
70
71 server := httptest.NewServer(handler)
72 defer server.Close()
73
74 url := server.URL + "/block/btc/" + hash.String()
75
76 first := get(t, url)
77
78 if first.status != http.StatusOK {
79 t.Fatalf("first request status %d, body %q", first.status, first.body)
80 }
81
82 if first.source != "node" {
83 t.Fatalf("first request came from %q, want the node", first.source)
84 }
85
86 if len(first.body) != 128 {
87 t.Fatalf("first request returned %d bytes", len(first.body))
88 }
89
90 second := get(t, url)
91
92 if second.status != http.StatusOK || second.source != "cache" {
93 t.Fatalf("second request: status %d, source %q", second.status, second.source)
94 }
95
96 if node.count() != 1 {
97 t.Fatalf("the node was read %d times, want one", node.count())
98 }
99 }
100
101 // TestAnotherChainIsRefused: one sidecar follows one chain, and a request for another is a
102 // deployment mistake rather than a cache miss.
103 func TestAnotherChainIsRefused(t *testing.T) {
104 hash := chainhash.HashH([]byte("block"))
105 _, handler := serviceFor(t, &stubBlocks{raw: map[string][]byte{hash.String(): {1, 2, 3}}})
106
107 server := httptest.NewServer(handler)
108 defer server.Close()
109
110 response := get(t, server.URL+"/block/blake/"+hash.String())
111
112 if response.status != http.StatusNotFound {
113 t.Fatalf("a request for another chain answered %d", response.status)
114 }
115 }
116
117 // TestABadHashIsRefused: the hash is parsed before anything is fetched.
118 func TestABadHashIsRefused(t *testing.T) {
119 _, handler := serviceFor(t, &stubBlocks{raw: map[string][]byte{}})
120
121 server := httptest.NewServer(handler)
122 defer server.Close()
123
124 response := get(t, server.URL+"/block/btc/not-a-hash")
125
126 if response.status != http.StatusBadRequest {
127 t.Fatalf("a malformed hash answered %d", response.status)
128 }
129 }
130
131 // TestAMissingBlockIs404: a hash the node does not have is not a server fault.
132 func TestAMissingBlockIs404(t *testing.T) {
133 hash := chainhash.HashH([]byte("missing"))
134 _, handler := serviceFor(t, &stubBlocks{raw: map[string][]byte{}})
135
136 server := httptest.NewServer(handler)
137 defer server.Close()
138
139 response := get(t, server.URL+"/block/btc/"+hash.String())
140
141 if response.status != http.StatusNotFound {
142 t.Fatalf("a block the node does not have answered %d", response.status)
143 }
144 }
145
146 // TestConcurrentRequestsForOneBlockAreOneNodeRead: ten clients asking for the tip block are
147 // still one fetch, which is the difference between a cache and a queue of node reads.
148 func TestConcurrentRequestsForOneBlockAreOneNodeRead(t *testing.T) {
149 hash := chainhash.HashH([]byte("hot"))
150 node := &stubBlocks{raw: map[string][]byte{hash.String(): bytes.Repeat([]byte{9}, 64)}}
151
152 _, handler := serviceFor(t, node)
153
154 server := httptest.NewServer(handler)
155 defer server.Close()
156
157 var wait sync.WaitGroup
158
159 for i := 0; i < 10; i++ {
160 wait.Add(1)
161
162 go func() {
163 defer wait.Done()
164
165 get(t, server.URL+"/block/btc/"+hash.String())
166 }()
167 }
168
169 wait.Wait()
170
171 if node.count() != 1 {
172 t.Fatalf("ten requests caused %d node reads", node.count())
173 }
174 }
175
176 // answer is one HTTP response, read out in full.
177 type answer struct {
178 status int
179 source string
180 body []byte
181 }
182
183 func get(t *testing.T, url string) answer {
184 t.Helper()
185
186 response, err := http.Get(url)
187
188 if err != nil {
189 t.Fatal(err)
190 }
191
192 defer response.Body.Close()
193
194 body, err := io.ReadAll(response.Body)
195
196 if err != nil {
197 t.Fatal(err)
198 }
199
200 return answer{status: response.StatusCode, source: response.Header.Get("X-Block-Source"), body: body}
201 }
202
203 // TestTheServiceIsReadableFromAPage: the client is a browser, and a cross-origin response
204 // without the header is a fetch that fails with a reason the page cannot see. The preflight
205 // has to answer too, because a GET with no custom headers still preflights when the page asks
206 // for a mode the browser considers non-simple.
207 func TestTheServiceIsReadableFromAPage(t *testing.T) {
208 hash := chainhash.HashH([]byte("cors"))
209 _, handler := serviceFor(t, &stubBlocks{raw: map[string][]byte{hash.String(): {1, 2, 3}}})
210
211 server := httptest.NewServer(handler)
212 defer server.Close()
213
214 response, err := http.Get(server.URL + "/block/btc/" + hash.String())
215
216 if err != nil {
217 t.Fatal(err)
218 }
219
220 response.Body.Close()
221
222 if got := response.Header.Get("Access-Control-Allow-Origin"); got != "*" {
223 t.Fatalf("GET allow-origin = %q", got)
224 }
225
226 preflight, err := http.NewRequest(http.MethodOptions, server.URL+"/block/btc/"+hash.String(), nil)
227
228 if err != nil {
229 t.Fatal(err)
230 }
231
232 answer, err := http.DefaultClient.Do(preflight)
233
234 if err != nil {
235 t.Fatal(err)
236 }
237
238 answer.Body.Close()
239
240 if answer.StatusCode != http.StatusNoContent {
241 t.Fatalf("preflight answered %d, want 204", answer.StatusCode)
242 }
243 }
244
245 // TestAChainAliasReachesTheService: the application calls the forked chain blake and its
246 // profile is xbt, so a request under either name has to reach the same service. A request for
247 // a different chain still does not.
248 func TestAChainAliasReachesTheService(t *testing.T) {
249 hash := chainhash.HashH([]byte("alias"))
250 node := &stubBlocks{raw: map[string][]byte{hash.String(): {1, 2, 3}}}
251
252 cache, err := blockcache.Open(blockcache.Config{Dir: t.TempDir(), MaxBytes: 1 << 20})
253
254 if err != nil {
255 t.Fatal(err)
256 }
257
258 defer cache.Close()
259
260 server := httptest.NewServer(newBlockService("xbt", node, cache, func(string, ...any) {}).handler())
261 defer server.Close()
262
263 if answer := get(t, server.URL+"/block/blake/"+hash.String()); answer.status != http.StatusOK {
264 t.Fatalf("blake alias answered %d", answer.status)
265 }
266
267 if answer := get(t, server.URL+"/block/xbt/"+hash.String()); answer.status != http.StatusOK {
268 t.Fatalf("xbt answered %d", answer.status)
269 }
270
271 if answer := get(t, server.URL+"/block/btc/"+hash.String()); answer.status != http.StatusNotFound {
272 t.Fatalf("another chain answered %d", answer.status)
273 }
274 }
275