package serve_test import ( "encoding/binary" "net/http/httptest" "path/filepath" "testing" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/neutrino" "git.smesh.lol/btcd-lite/internal/chunk" "git.smesh.lol/btcd-lite/internal/filterstore" "git.smesh.lol/btcd-lite/internal/serve" "git.smesh.lol/btcd-lite/internal/service" "git.smesh.lol/btcd-lite/internal/store" ) // v2Version is the fork's version field: the flag bit over version 2, read as // the signed int32 the field is. var v2Version = func() int32 { v := uint32(btcwire.HeaderV2Flag) | 2; return int32(v) }() // headerAt is a distinct valid header per height. It is a Bitcoin header, which // is what the two chains carry below the fork. func headerAt(i uint32) btcwire.BlockHeader { return btcwire.BlockHeader{ Version: 1, MerkleRoot: chainhash.Hash{byte(i), byte(i >> 8)}, Timestamp: 1231006505 + i, Bits: 0x1d00ffff, Nonce: i, } } // build fills one body store and two header stores with 250 heights of the same // chain. Below the fork the two chains are the same chain, so the same bodies // and the same headers serve both: that is the layout the consolidation is for. func build(t *testing.T) (*serve.View, []byte) { t.Helper() dir := t.TempDir() bodies, err := store.NewBlockStore(filepath.Join(dir, "blocks")) if err != nil { t.Fatal(err) } t.Cleanup(func() { bodies.Close() }) var raw []byte var hdrs []btcwire.BlockHeader for i := uint32(0); i < 250; i++ { h := headerAt(i) hdrs = append(hdrs, h) b := append(h.SerializeAll(), make([]byte, 10+int(i%20))...) raw = binary.LittleEndian.AppendUint32(raw, uint32(len(b))) raw = append(raw, b...) if err := bodies.PutBlock(h.BlockHash(), b); err != nil { t.Fatal(err) } } chains := map[string]*store.HeaderStore{} for _, name := range []string{"btc", "xbt"} { hs, err := store.NewHeaderStore(filepath.Join(dir, "headers", name)) if err != nil { t.Fatal(err) } t.Cleanup(func() { hs.Close() }) if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil { t.Fatal(err) } if err := hs.PutHeaders(0, hdrs); err != nil { t.Fatal(err) } chains[name] = hs } return serve.New(chains, bodies), raw } // split walks a length-prefixed stream and returns its records. func split(raw []byte, n int) [][]byte { out := make([][]byte, 0, n) at := 0 for at < len(raw) { ln := int(binary.LittleEndian.Uint32(raw[at:])) out = append(out, raw[at+4:at+4+ln]) at += 4 + ln } return out } // TestBlocksServedByChunk: a block range is cut into the plan's hundred-block // chunks, the service names them, and each name serves bytes that hash to it // and hold exactly the blocks of its range. func TestBlocksServedByChunk(t *testing.T) { v, raw := build(t) want := split(raw, 250) h := service.Handler(v) w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest("GET", "/v1/chains/btc/blk/0-250", nil)) if w.Code != 200 { t.Fatalf("range status %d: %s", w.Code, w.Body) } var listed struct { Chunks []string `json:"chunks"` } if err := decodeJSON(w.Body.Bytes(), &listed); err != nil { t.Fatal(err) } if len(listed.Chunks) != 3 { t.Fatalf("%d chunks for 250 blocks", len(listed.Chunks)) } seen := 0 for _, name := range listed.Chunks { w2 := httptest.NewRecorder() h.ServeHTTP(w2, httptest.NewRequest("GET", "/v1/chunks/"+name, nil)) if w2.Code != 200 { t.Fatalf("chunk %s: %d", name, w2.Code) } if got := chunk.Name(w2.Body.Bytes()).String(); got != name { t.Fatalf("chunk %s served %s", name, got) } for _, b := range split(w2.Body.Bytes(), 0) { if string(b) != string(want[seen]) { t.Fatalf("block %d differs", seen) } seen++ } } if seen != 250 { t.Fatalf("%d blocks came back, the store has 250", seen) } } // TestOneBodyStoreTwoChains: the same range of both chains cuts to the same // chunks, because the bodies are the same bytes. That is what one copy means. func TestOneBodyStoreTwoChains(t *testing.T) { v, _ := build(t) btc, err := v.Range(chunk.Blocks, "btc", 0, 25) if err != nil { t.Fatal(err) } xbt, err := v.Range(chunk.Blocks, "xbt", 0, 25) if err != nil { t.Fatalf("the second chain was refused: %v", err) } if len(btc) != len(xbt) { t.Fatalf("%d chunks for btc, %d for xbt", len(btc), len(xbt)) } for i := range btc { if btc[i].Name() != xbt[i].Name() { t.Fatalf("chunk %d differs between the chains", i) } } if got, want := v.Bodies.Len(), 250; got != want { t.Fatalf("the body store holds %d blocks for two chains of 250", got) } } // TestHeadersServed: the header chunks carry each header's own bytes, read from // the bodies where they are stored. func TestHeadersServed(t *testing.T) { v, raw := build(t) chunks, err := v.Range(chunk.Headers, "btc", 10, 20) if err != nil { t.Fatal(err) } if len(chunks) != 1 || chunks[0].From != 10 || chunks[0].To != 20 { t.Fatalf("%d chunks for headers 10-20", len(chunks)) } blocks := split(raw, 0) for i := 0; i < 10; i++ { got := chunks[0].Raw[i*80 : (i+1)*80] if string(got) != string(blocks[10+i][:80]) { t.Fatalf("header %d is not the body's prefix", 10+i) } } } // TestHeaderFallsBackToTheStore: a chain whose bodies are not stored yet still // serves headers out of its header store, in the 80-byte form, which is the // only form a header store holds. func TestHeaderFallsBackToTheStore(t *testing.T) { v, _ := build(t) // A chain with headers and no bodies at all. dir := t.TempDir() hs, err := store.NewHeaderStore(filepath.Join(dir, "headers", "bare")) if err != nil { t.Fatal(err) } defer hs.Close() var hdrs []btcwire.BlockHeader for i := uint32(0); i < 5; i++ { hdrs = append(hdrs, headerAt(i)) } if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil { t.Fatal(err) } if err := hs.PutHeaders(0, hdrs); err != nil { t.Fatal(err) } v.Headers["bare"] = hs chunks, err := v.Range(chunk.Headers, "bare", 1, 4) if err != nil { t.Fatalf("the fallback refused: %v", err) } if len(chunks) != 1 || chunks[0].To != 4 { t.Fatalf("fallback chunk %+v", chunks) } if string(chunks[0].Raw) != string(hdrs[1].SerializeAll())+string(hdrs[2].SerializeAll())+string(hdrs[3].SerializeAll()) { t.Fatal("the fallback served other bytes than the store's") } } // TestForkHeaderServedAt164: a version 2 body's header is served at its own // width, read from the body, and hashes to the fork's construction. The header // store holds the same header at 164 bytes, because a record carries its own // length. func TestForkHeaderServedAt164(t *testing.T) { dir := t.TempDir() bodies, err := store.NewBlockStore(filepath.Join(dir, "blocks")) if err != nil { t.Fatal(err) } defer bodies.Close() var hdrs []btcwire.BlockHeader for i := 0; i < 3; i++ { h := btcwire.BlockHeader{ Version: v2Version, MerkleRoot: chainhash.Hash{byte(i)}, Timestamp: 1231006505, Bits: 0x1d00ffff, Nonce: uint32(i), V2: &btcwire.HeaderV2{ Nonce2: uint32(i), Height: int32(961640 + i), MMRHS: chainhash.Hash{byte(0xff - i)}, }, } hdrs = append(hdrs, h) body := append(h.SerializeAll(), 0xde, 0xad) if err := bodies.PutBlock(h.BlockHash(), body); err != nil { t.Fatal(err) } } hs, err := store.NewHeaderStore(filepath.Join(dir, "headers", "xbt")) if err != nil { t.Fatal(err) } defer hs.Close() if err := hs.SetAnchor(neutrino.Anchor{Height: 961640, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil { t.Fatal(err) } if err := hs.PutHeaders(961640, hdrs); err != nil { t.Fatalf("the fork's headers were refused: %v", err) } v := serve.New(map[string]*store.HeaderStore{"xbt": hs}, bodies) chunks, err := v.Range(chunk.Headers, "xbt", 961640, 961643) if err != nil { t.Fatalf("a 164-byte chain served nothing: %v", err) } if got := len(chunks[0].Raw); got != 3*btcwire.BlockHeaderV2Size { t.Fatalf("served %d bytes for three v2 headers", got) } if serve.HeaderHash(chunks[0].Raw[:btcwire.BlockHeaderV2Size]) != hdrs[0].BlockHash() { t.Fatal("the served v2 header does not hash to the block's own hash") } } // TestChainNotHeld: a name the view does not hold is refused, naming what it // does hold. func TestChainNotHeld(t *testing.T) { v, _ := build(t) _, err := v.Range(chunk.Blocks, "ltc", 0, 10) if err == nil { t.Fatal("a chain the view does not hold was served") } if !contains(err.Error(), "btc") || !contains(err.Error(), "xbt") { t.Fatalf("the refusal does not name the chains it holds: %v", err) } } 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 } func decodeJSON(b []byte, v any) error { return jsonUnmarshal(b, v) } // TestFiltersSharedByChains: a filter is keyed by its block's hash, so the same // range of two chains that carry the same blocks cuts to one chunk and serves // one set of bytes. func TestFiltersSharedByChains(t *testing.T) { v, _ := build(t) dir := t.TempDir() fs, err := filterstore.Open(dir) if err != nil { t.Fatal(err) } defer fs.Close() // One distinct filter per height, filed under the block's hash. for i := uint32(0); i < 25; i++ { h := headerAt(i) f := binary.LittleEndian.AppendUint32(nil, i) f = append(f, make([]byte, 8)...) if err := fs.Put(h.BlockHash(), f); err != nil { t.Fatal(err) } } v.Filters = fs btc, err := v.Range(chunk.Filters, "btc", 0, 25) if err != nil { t.Fatal(err) } xbt, err := v.Range(chunk.Filters, "xbt", 0, 25) if err != nil { t.Fatal(err) } if len(btc) != 1 || len(xbt) != 1 { t.Fatalf("%d and %d filter chunks for 25 filters", len(btc), len(xbt)) } if btc[0].Name() != xbt[0].Name() { t.Fatal("the two chains cut different filter chunks for the same blocks") } // The chunk is the filters length-prefixed, in height order. at := 0 for i := uint32(0); i < 25; i++ { n := binary.LittleEndian.Uint32(btc[0].Raw[at:]) if n != 12 { t.Fatalf("filter %d is %d bytes", i, n) } if got := binary.LittleEndian.Uint32(btc[0].Raw[at+4:]); got != i { t.Fatalf("filter %d holds %d", i, got) } at += 4 + int(n) } if at != len(btc[0].Raw) { t.Fatalf("the chunk has %d trailing bytes", len(btc[0].Raw)-at) } // A view with no filter store serves none rather than an empty chunk. v.Filters = nil if _, err := v.Range(chunk.Filters, "btc", 0, 25); err == nil { t.Fatal("a view with no filters answered a filter range") } }