1 package serve_test
2 3 import (
4 "encoding/binary"
5 "net/http/httptest"
6 "path/filepath"
7 "testing"
8 9 "git.smesh.lol/nostrino/pkg/btcwire"
10 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
11 "git.smesh.lol/nostrino/pkg/neutrino"
12 13 "git.smesh.lol/btcd-lite/internal/chunk"
14 "git.smesh.lol/btcd-lite/internal/filterstore"
15 "git.smesh.lol/btcd-lite/internal/serve"
16 "git.smesh.lol/btcd-lite/internal/service"
17 "git.smesh.lol/btcd-lite/internal/store"
18 )
19 20 // v2Version is the fork's version field: the flag bit over version 2, read as
21 // the signed int32 the field is.
22 var v2Version = func() int32 { v := uint32(btcwire.HeaderV2Flag) | 2; return int32(v) }()
23 24 // headerAt is a distinct valid header per height. It is a Bitcoin header, which
25 // is what the two chains carry below the fork.
26 func headerAt(i uint32) btcwire.BlockHeader {
27 return btcwire.BlockHeader{
28 Version: 1,
29 MerkleRoot: chainhash.Hash{byte(i), byte(i >> 8)},
30 Timestamp: 1231006505 + i,
31 Bits: 0x1d00ffff,
32 Nonce: i,
33 }
34 }
35 36 // build fills one body store and two header stores with 250 heights of the same
37 // chain. Below the fork the two chains are the same chain, so the same bodies
38 // and the same headers serve both: that is the layout the consolidation is for.
39 func build(t *testing.T) (*serve.View, []byte) {
40 t.Helper()
41 dir := t.TempDir()
42 bodies, err := store.NewBlockStore(filepath.Join(dir, "blocks"))
43 if err != nil {
44 t.Fatal(err)
45 }
46 t.Cleanup(func() { bodies.Close() })
47 var raw []byte
48 var hdrs []btcwire.BlockHeader
49 for i := uint32(0); i < 250; i++ {
50 h := headerAt(i)
51 hdrs = append(hdrs, h)
52 b := append(h.SerializeAll(), make([]byte, 10+int(i%20))...)
53 raw = binary.LittleEndian.AppendUint32(raw, uint32(len(b)))
54 raw = append(raw, b...)
55 if err := bodies.PutBlock(h.BlockHash(), b); err != nil {
56 t.Fatal(err)
57 }
58 }
59 chains := map[string]*store.HeaderStore{}
60 for _, name := range []string{"btc", "xbt"} {
61 hs, err := store.NewHeaderStore(filepath.Join(dir, "headers", name))
62 if err != nil {
63 t.Fatal(err)
64 }
65 t.Cleanup(func() { hs.Close() })
66 if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil {
67 t.Fatal(err)
68 }
69 if err := hs.PutHeaders(0, hdrs); err != nil {
70 t.Fatal(err)
71 }
72 chains[name] = hs
73 }
74 return serve.New(chains, bodies), raw
75 }
76 77 // split walks a length-prefixed stream and returns its records.
78 func split(raw []byte, n int) [][]byte {
79 out := make([][]byte, 0, n)
80 at := 0
81 for at < len(raw) {
82 ln := int(binary.LittleEndian.Uint32(raw[at:]))
83 out = append(out, raw[at+4:at+4+ln])
84 at += 4 + ln
85 }
86 return out
87 }
88 89 // TestBlocksServedByChunk: a block range is cut into the plan's hundred-block
90 // chunks, the service names them, and each name serves bytes that hash to it
91 // and hold exactly the blocks of its range.
92 func TestBlocksServedByChunk(t *testing.T) {
93 v, raw := build(t)
94 want := split(raw, 250)
95 h := service.Handler(v)
96 w := httptest.NewRecorder()
97 h.ServeHTTP(w, httptest.NewRequest("GET", "/v1/chains/btc/blk/0-250", nil))
98 if w.Code != 200 {
99 t.Fatalf("range status %d: %s", w.Code, w.Body)
100 }
101 var listed struct {
102 Chunks []string `json:"chunks"`
103 }
104 if err := decodeJSON(w.Body.Bytes(), &listed); err != nil {
105 t.Fatal(err)
106 }
107 if len(listed.Chunks) != 3 {
108 t.Fatalf("%d chunks for 250 blocks", len(listed.Chunks))
109 }
110 seen := 0
111 for _, name := range listed.Chunks {
112 w2 := httptest.NewRecorder()
113 h.ServeHTTP(w2, httptest.NewRequest("GET", "/v1/chunks/"+name, nil))
114 if w2.Code != 200 {
115 t.Fatalf("chunk %s: %d", name, w2.Code)
116 }
117 if got := chunk.Name(w2.Body.Bytes()).String(); got != name {
118 t.Fatalf("chunk %s served %s", name, got)
119 }
120 for _, b := range split(w2.Body.Bytes(), 0) {
121 if string(b) != string(want[seen]) {
122 t.Fatalf("block %d differs", seen)
123 }
124 seen++
125 }
126 }
127 if seen != 250 {
128 t.Fatalf("%d blocks came back, the store has 250", seen)
129 }
130 }
131 132 // TestOneBodyStoreTwoChains: the same range of both chains cuts to the same
133 // chunks, because the bodies are the same bytes. That is what one copy means.
134 func TestOneBodyStoreTwoChains(t *testing.T) {
135 v, _ := build(t)
136 btc, err := v.Range(chunk.Blocks, "btc", 0, 25)
137 if err != nil {
138 t.Fatal(err)
139 }
140 xbt, err := v.Range(chunk.Blocks, "xbt", 0, 25)
141 if err != nil {
142 t.Fatalf("the second chain was refused: %v", err)
143 }
144 if len(btc) != len(xbt) {
145 t.Fatalf("%d chunks for btc, %d for xbt", len(btc), len(xbt))
146 }
147 for i := range btc {
148 if btc[i].Name() != xbt[i].Name() {
149 t.Fatalf("chunk %d differs between the chains", i)
150 }
151 }
152 if got, want := v.Bodies.Len(), 250; got != want {
153 t.Fatalf("the body store holds %d blocks for two chains of 250", got)
154 }
155 }
156 157 // TestHeadersServed: the header chunks carry each header's own bytes, read from
158 // the bodies where they are stored.
159 func TestHeadersServed(t *testing.T) {
160 v, raw := build(t)
161 chunks, err := v.Range(chunk.Headers, "btc", 10, 20)
162 if err != nil {
163 t.Fatal(err)
164 }
165 if len(chunks) != 1 || chunks[0].From != 10 || chunks[0].To != 20 {
166 t.Fatalf("%d chunks for headers 10-20", len(chunks))
167 }
168 blocks := split(raw, 0)
169 for i := 0; i < 10; i++ {
170 got := chunks[0].Raw[i*80 : (i+1)*80]
171 if string(got) != string(blocks[10+i][:80]) {
172 t.Fatalf("header %d is not the body's prefix", 10+i)
173 }
174 }
175 }
176 177 // TestHeaderFallsBackToTheStore: a chain whose bodies are not stored yet still
178 // serves headers out of its header store, in the 80-byte form, which is the
179 // only form a header store holds.
180 func TestHeaderFallsBackToTheStore(t *testing.T) {
181 v, _ := build(t)
182 // A chain with headers and no bodies at all.
183 dir := t.TempDir()
184 hs, err := store.NewHeaderStore(filepath.Join(dir, "headers", "bare"))
185 if err != nil {
186 t.Fatal(err)
187 }
188 defer hs.Close()
189 var hdrs []btcwire.BlockHeader
190 for i := uint32(0); i < 5; i++ {
191 hdrs = append(hdrs, headerAt(i))
192 }
193 if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil {
194 t.Fatal(err)
195 }
196 if err := hs.PutHeaders(0, hdrs); err != nil {
197 t.Fatal(err)
198 }
199 v.Headers["bare"] = hs
200 chunks, err := v.Range(chunk.Headers, "bare", 1, 4)
201 if err != nil {
202 t.Fatalf("the fallback refused: %v", err)
203 }
204 if len(chunks) != 1 || chunks[0].To != 4 {
205 t.Fatalf("fallback chunk %+v", chunks)
206 }
207 if string(chunks[0].Raw) != string(hdrs[1].SerializeAll())+string(hdrs[2].SerializeAll())+string(hdrs[3].SerializeAll()) {
208 t.Fatal("the fallback served other bytes than the store's")
209 }
210 }
211 212 // TestForkHeaderServedAt164: a version 2 body's header is served at its own
213 // width, read from the body, and hashes to the fork's construction. The header
214 // store holds the same header at 164 bytes, because a record carries its own
215 // length.
216 func TestForkHeaderServedAt164(t *testing.T) {
217 dir := t.TempDir()
218 bodies, err := store.NewBlockStore(filepath.Join(dir, "blocks"))
219 if err != nil {
220 t.Fatal(err)
221 }
222 defer bodies.Close()
223 var hdrs []btcwire.BlockHeader
224 for i := 0; i < 3; i++ {
225 h := btcwire.BlockHeader{
226 Version: v2Version,
227 MerkleRoot: chainhash.Hash{byte(i)},
228 Timestamp: 1231006505,
229 Bits: 0x1d00ffff,
230 Nonce: uint32(i),
231 V2: &btcwire.HeaderV2{
232 Nonce2: uint32(i), Height: int32(961640 + i),
233 MMRHS: chainhash.Hash{byte(0xff - i)},
234 },
235 }
236 hdrs = append(hdrs, h)
237 body := append(h.SerializeAll(), 0xde, 0xad)
238 if err := bodies.PutBlock(h.BlockHash(), body); err != nil {
239 t.Fatal(err)
240 }
241 }
242 hs, err := store.NewHeaderStore(filepath.Join(dir, "headers", "xbt"))
243 if err != nil {
244 t.Fatal(err)
245 }
246 defer hs.Close()
247 if err := hs.SetAnchor(neutrino.Anchor{Height: 961640, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil {
248 t.Fatal(err)
249 }
250 if err := hs.PutHeaders(961640, hdrs); err != nil {
251 t.Fatalf("the fork's headers were refused: %v", err)
252 }
253 v := serve.New(map[string]*store.HeaderStore{"xbt": hs}, bodies)
254 chunks, err := v.Range(chunk.Headers, "xbt", 961640, 961643)
255 if err != nil {
256 t.Fatalf("a 164-byte chain served nothing: %v", err)
257 }
258 if got := len(chunks[0].Raw); got != 3*btcwire.BlockHeaderV2Size {
259 t.Fatalf("served %d bytes for three v2 headers", got)
260 }
261 if serve.HeaderHash(chunks[0].Raw[:btcwire.BlockHeaderV2Size]) != hdrs[0].BlockHash() {
262 t.Fatal("the served v2 header does not hash to the block's own hash")
263 }
264 }
265 266 // TestChainNotHeld: a name the view does not hold is refused, naming what it
267 // does hold.
268 func TestChainNotHeld(t *testing.T) {
269 v, _ := build(t)
270 _, err := v.Range(chunk.Blocks, "ltc", 0, 10)
271 if err == nil {
272 t.Fatal("a chain the view does not hold was served")
273 }
274 if !contains(err.Error(), "btc") || !contains(err.Error(), "xbt") {
275 t.Fatalf("the refusal does not name the chains it holds: %v", err)
276 }
277 }
278 279 func contains(s, sub string) bool {
280 for i := 0; i+len(sub) <= len(s); i++ {
281 if s[i:i+len(sub)] == sub {
282 return true
283 }
284 }
285 return false
286 }
287 288 func decodeJSON(b []byte, v any) error { return jsonUnmarshal(b, v) }
289 290 // TestFiltersSharedByChains: a filter is keyed by its block's hash, so the same
291 // range of two chains that carry the same blocks cuts to one chunk and serves
292 // one set of bytes.
293 func TestFiltersSharedByChains(t *testing.T) {
294 v, _ := build(t)
295 dir := t.TempDir()
296 fs, err := filterstore.Open(dir)
297 if err != nil {
298 t.Fatal(err)
299 }
300 defer fs.Close()
301 // One distinct filter per height, filed under the block's hash.
302 for i := uint32(0); i < 25; i++ {
303 h := headerAt(i)
304 f := binary.LittleEndian.AppendUint32(nil, i)
305 f = append(f, make([]byte, 8)...)
306 if err := fs.Put(h.BlockHash(), f); err != nil {
307 t.Fatal(err)
308 }
309 }
310 v.Filters = fs
311 btc, err := v.Range(chunk.Filters, "btc", 0, 25)
312 if err != nil {
313 t.Fatal(err)
314 }
315 xbt, err := v.Range(chunk.Filters, "xbt", 0, 25)
316 if err != nil {
317 t.Fatal(err)
318 }
319 if len(btc) != 1 || len(xbt) != 1 {
320 t.Fatalf("%d and %d filter chunks for 25 filters", len(btc), len(xbt))
321 }
322 if btc[0].Name() != xbt[0].Name() {
323 t.Fatal("the two chains cut different filter chunks for the same blocks")
324 }
325 // The chunk is the filters length-prefixed, in height order.
326 at := 0
327 for i := uint32(0); i < 25; i++ {
328 n := binary.LittleEndian.Uint32(btc[0].Raw[at:])
329 if n != 12 {
330 t.Fatalf("filter %d is %d bytes", i, n)
331 }
332 if got := binary.LittleEndian.Uint32(btc[0].Raw[at+4:]); got != i {
333 t.Fatalf("filter %d holds %d", i, got)
334 }
335 at += 4 + int(n)
336 }
337 if at != len(btc[0].Raw) {
338 t.Fatalf("the chunk has %d trailing bytes", len(btc[0].Raw)-at)
339 }
340 // A view with no filter store serves none rather than an empty chunk.
341 v.Filters = nil
342 if _, err := v.Range(chunk.Filters, "btc", 0, 25); err == nil {
343 t.Fatal("a view with no filters answered a filter range")
344 }
345 }
346