package main import ( "bytes" "context" "fmt" "io" "net/http" "net/http/httptest" "sync" "testing" "git.smesh.lol/nostrino/pkg/blockcache" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // stubBlocks is a node that holds whatever the test put in it and counts reads. type stubBlocks struct { mu sync.Mutex calls int raw map[string][]byte } func (s *stubBlocks) blockByHash(_ context.Context, hash chainhash.Hash) ([]byte, error) { s.mu.Lock() defer s.mu.Unlock() s.calls++ raw, ok := s.raw[hash.String()] if !ok { return nil, fmt.Errorf("getblock %s: not found", hash.String()) } return raw, nil } func (s *stubBlocks) count() int { s.mu.Lock() defer s.mu.Unlock() return s.calls } // serviceFor builds a service over a stub node and a cache in a temporary directory. func serviceFor(t *testing.T, node blockReader) (*blockService, http.Handler) { t.Helper() cache, err := blockcache.Open(blockcache.Config{Dir: t.TempDir(), MaxBytes: 1 << 20}) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = cache.Close() }) service := newBlockService("btc", node, cache, func(string, ...any) {}) return service, service.handler() } // TestTheFirstRequestFetchesAndTheSecondIsACacheHit: the node is read once, and the block the // first client paid for is what the next one gets. func TestTheFirstRequestFetchesAndTheSecondIsACacheHit(t *testing.T) { hash := chainhash.HashH([]byte("block")) node := &stubBlocks{raw: map[string][]byte{hash.String(): bytes.Repeat([]byte{7}, 128)}} _, handler := serviceFor(t, node) server := httptest.NewServer(handler) defer server.Close() url := server.URL + "/block/btc/" + hash.String() first := get(t, url) if first.status != http.StatusOK { t.Fatalf("first request status %d, body %q", first.status, first.body) } if first.source != "node" { t.Fatalf("first request came from %q, want the node", first.source) } if len(first.body) != 128 { t.Fatalf("first request returned %d bytes", len(first.body)) } second := get(t, url) if second.status != http.StatusOK || second.source != "cache" { t.Fatalf("second request: status %d, source %q", second.status, second.source) } if node.count() != 1 { t.Fatalf("the node was read %d times, want one", node.count()) } } // TestAnotherChainIsRefused: one sidecar follows one chain, and a request for another is a // deployment mistake rather than a cache miss. func TestAnotherChainIsRefused(t *testing.T) { hash := chainhash.HashH([]byte("block")) _, handler := serviceFor(t, &stubBlocks{raw: map[string][]byte{hash.String(): {1, 2, 3}}}) server := httptest.NewServer(handler) defer server.Close() response := get(t, server.URL+"/block/blake/"+hash.String()) if response.status != http.StatusNotFound { t.Fatalf("a request for another chain answered %d", response.status) } } // TestABadHashIsRefused: the hash is parsed before anything is fetched. func TestABadHashIsRefused(t *testing.T) { _, handler := serviceFor(t, &stubBlocks{raw: map[string][]byte{}}) server := httptest.NewServer(handler) defer server.Close() response := get(t, server.URL+"/block/btc/not-a-hash") if response.status != http.StatusBadRequest { t.Fatalf("a malformed hash answered %d", response.status) } } // TestAMissingBlockIs404: a hash the node does not have is not a server fault. func TestAMissingBlockIs404(t *testing.T) { hash := chainhash.HashH([]byte("missing")) _, handler := serviceFor(t, &stubBlocks{raw: map[string][]byte{}}) server := httptest.NewServer(handler) defer server.Close() response := get(t, server.URL+"/block/btc/"+hash.String()) if response.status != http.StatusNotFound { t.Fatalf("a block the node does not have answered %d", response.status) } } // TestConcurrentRequestsForOneBlockAreOneNodeRead: ten clients asking for the tip block are // still one fetch, which is the difference between a cache and a queue of node reads. func TestConcurrentRequestsForOneBlockAreOneNodeRead(t *testing.T) { hash := chainhash.HashH([]byte("hot")) node := &stubBlocks{raw: map[string][]byte{hash.String(): bytes.Repeat([]byte{9}, 64)}} _, handler := serviceFor(t, node) server := httptest.NewServer(handler) defer server.Close() var wait sync.WaitGroup for i := 0; i < 10; i++ { wait.Add(1) go func() { defer wait.Done() get(t, server.URL+"/block/btc/"+hash.String()) }() } wait.Wait() if node.count() != 1 { t.Fatalf("ten requests caused %d node reads", node.count()) } } // answer is one HTTP response, read out in full. type answer struct { status int source string body []byte } func get(t *testing.T, url string) answer { t.Helper() response, err := http.Get(url) if err != nil { t.Fatal(err) } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { t.Fatal(err) } return answer{status: response.StatusCode, source: response.Header.Get("X-Block-Source"), body: body} } // TestTheServiceIsReadableFromAPage: the client is a browser, and a cross-origin response // without the header is a fetch that fails with a reason the page cannot see. The preflight // has to answer too, because a GET with no custom headers still preflights when the page asks // for a mode the browser considers non-simple. func TestTheServiceIsReadableFromAPage(t *testing.T) { hash := chainhash.HashH([]byte("cors")) _, handler := serviceFor(t, &stubBlocks{raw: map[string][]byte{hash.String(): {1, 2, 3}}}) server := httptest.NewServer(handler) defer server.Close() response, err := http.Get(server.URL + "/block/btc/" + hash.String()) if err != nil { t.Fatal(err) } response.Body.Close() if got := response.Header.Get("Access-Control-Allow-Origin"); got != "*" { t.Fatalf("GET allow-origin = %q", got) } preflight, err := http.NewRequest(http.MethodOptions, server.URL+"/block/btc/"+hash.String(), nil) if err != nil { t.Fatal(err) } answer, err := http.DefaultClient.Do(preflight) if err != nil { t.Fatal(err) } answer.Body.Close() if answer.StatusCode != http.StatusNoContent { t.Fatalf("preflight answered %d, want 204", answer.StatusCode) } } // TestAChainAliasReachesTheService: the application calls the forked chain blake and its // profile is xbt, so a request under either name has to reach the same service. A request for // a different chain still does not. func TestAChainAliasReachesTheService(t *testing.T) { hash := chainhash.HashH([]byte("alias")) node := &stubBlocks{raw: map[string][]byte{hash.String(): {1, 2, 3}}} cache, err := blockcache.Open(blockcache.Config{Dir: t.TempDir(), MaxBytes: 1 << 20}) if err != nil { t.Fatal(err) } defer cache.Close() server := httptest.NewServer(newBlockService("xbt", node, cache, func(string, ...any) {}).handler()) defer server.Close() if answer := get(t, server.URL+"/block/blake/"+hash.String()); answer.status != http.StatusOK { t.Fatalf("blake alias answered %d", answer.status) } if answer := get(t, server.URL+"/block/xbt/"+hash.String()); answer.status != http.StatusOK { t.Fatalf("xbt answered %d", answer.status) } if answer := get(t, server.URL+"/block/btc/"+hash.String()); answer.status != http.StatusNotFound { t.Fatalf("another chain answered %d", answer.status) } }