seed_test.go raw

   1  package gate
   2  
   3  import (
   4  	"encoding/binary"
   5  	"encoding/json"
   6  	"fmt"
   7  	"io"
   8  	"net/http"
   9  	"net/http/httptest"
  10  	"testing"
  11  
  12  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  13  
  14  	"git.smesh.lol/btcd-lite/internal/chunk"
  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  // TestSeedFromService fills a body store from a node, serves it over the
  21  // service's HTTP contract, and hands the same blocks to a second store through
  22  // that contract. The second store's blocks must be the node's bytes.
  23  //
  24  // The first half needs the node's RPC rather than its peer, because the peer
  25  // does not answer on this machine (see TestPeerAcceptsWhatWeDoNot). What it
  26  // proves is the seeding path: a chunk cut on one instance, named by its hash,
  27  // fetched and checked by another, and filed under the hash the header chain
  28  // gives.
  29  func TestSeedFromService(t *testing.T) {
  30  	n := openNode(t)
  31  	tip, err := n.BlockCount()
  32  	if err != nil {
  33  		t.Fatal(err)
  34  	}
  35  	if tip < 50 {
  36  		t.Skipf("the node has %d blocks; the gate wants at least 50", tip)
  37  	}
  38  
  39  	// Instance A: blocks from the node's RPC, filed under their own hashes, at
  40  	// their heights.
  41  	dirA := t.TempDir()
  42  	headersA, err := store.NewHeaderStore(dirA + "/headers/btc")
  43  	if err != nil {
  44  		t.Fatal(err)
  45  	}
  46  	defer headersA.Close()
  47  	bodiesA, err := store.NewBlockStore(dirA + "/blocks")
  48  	if err != nil {
  49  		t.Fatal(err)
  50  	}
  51  	defer bodiesA.Close()
  52  
  53  	want := map[int32][]byte{}
  54  	for h := uint32(0); h <= tip; h++ {
  55  		hashHex, err := n.BlockHash(h)
  56  		if err != nil {
  57  			t.Fatal(err)
  58  		}
  59  		hash, err := chainhash.NewHashFromStr(hashHex)
  60  		if err != nil {
  61  			t.Fatal(err)
  62  		}
  63  		raw, err := n.BlockRaw(hashHex)
  64  		if err != nil {
  65  			t.Fatal(err)
  66  		}
  67  		if err := bodiesA.PutBlock(*hash, raw); err != nil {
  68  			t.Fatalf("put %d: %v", h, err)
  69  		}
  70  		want[int32(h)] = raw
  71  	}
  72  
  73  	seedHeaderChain(t, headersA, func(h uint32) []byte { return want[int32(h)] }, uint32(tip))
  74  	// Instance A serves what it holds.
  75  	view := serve.New(map[string]*store.HeaderStore{"btc": headersA}, bodiesA)
  76  	srv := httptest.NewServer(service.Handler(view))
  77  	defer srv.Close()
  78  
  79  	// Instance B: a body store filled from the service, checking every chunk
  80  	// against the name it asked for.
  81  	bodiesB, err := store.NewBlockStore(t.TempDir() + "/blocks")
  82  	if err != nil {
  83  		t.Fatal(err)
  84  	}
  85  	defer bodiesB.Close()
  86  	fill := func(from, to uint32) {
  87  		names, err := listChunks(srv.URL, "btc", chunk.Blocks.String(), from, to)
  88  		if err != nil {
  89  			t.Fatalf("list %d-%d: %v", from, to, err)
  90  		}
  91  		for _, name := range names {
  92  			raw, err := fetchChunk(srv.URL, name)
  93  			if err != nil {
  94  				t.Fatalf("chunk %s: %v", name, err)
  95  			}
  96  			if got := chunk.Name(raw).String(); got != name {
  97  				t.Fatalf("chunk %s hashes to %s", name, got)
  98  			}
  99  			at := 0
 100  			for at < len(raw) {
 101  				ln := int(binary.LittleEndian.Uint32(raw[at:]))
 102  				block := raw[at+4 : at+4+ln]
 103  				at += 4 + ln
 104  				h := serve.HeaderHash(block)
 105  				if err := bodiesB.PutBlock(h, block); err != nil && err != store.ErrBlockExists {
 106  					t.Fatalf("put: %v", err)
 107  				}
 108  			}
 109  		}
 110  	}
 111  	fill(0, 30)
 112  	if bodiesB.Len() != 30 {
 113  		t.Fatalf("B holds %d blocks after the first seed, want 30", bodiesB.Len())
 114  	}
 115  	// A second fill of the same range is a no-op: the names are the content.
 116  	fill(0, 30)
 117  	if bodiesB.Len() != 30 {
 118  		t.Fatalf("B holds %d blocks after a repeated seed", bodiesB.Len())
 119  	}
 120  
 121  	// Every block B holds is the node's, byte for byte, under the node's hash.
 122  	for h := int32(0); h < 30; h++ {
 123  		hash := chainhash.DoubleHashH(want[h][:80])
 124  		got, err := bodiesB.GetBlock(hash)
 125  		if err != nil {
 126  			t.Fatalf("B block %d: %v", h, err)
 127  		}
 128  		if string(got) != string(want[h]) {
 129  			t.Fatalf("B block %d is not the node's", h)
 130  		}
 131  	}
 132  	t.Logf("B was seeded with 30 of the node's %d blocks from A's service, each one the node's bytes", tip)
 133  }
 134  
 135  func listChunks(base, chainName, kind string, from, to uint32) ([]string, error) {
 136  	u := fmt.Sprintf("%s/v1/chains/%s/%s/%d-%d", base, chainName, kind, from, to)
 137  	resp, err := http.Get(u)
 138  	if err != nil {
 139  		return nil, err
 140  	}
 141  	defer resp.Body.Close()
 142  	body, _ := io.ReadAll(resp.Body)
 143  	if resp.StatusCode != http.StatusOK {
 144  		return nil, fmt.Errorf("%s: %d %s", u, resp.StatusCode, body)
 145  	}
 146  	var listed struct {
 147  		Chunks []string `json:"chunks"`
 148  	}
 149  	if err := json.Unmarshal(body, &listed); err != nil {
 150  		return nil, err
 151  	}
 152  	return listed.Chunks, nil
 153  }
 154  
 155  func fetchChunk(base, name string) ([]byte, error) {
 156  	resp, err := http.Get(base + "/v1/chunks/" + name)
 157  	if err != nil {
 158  		return nil, err
 159  	}
 160  	defer resp.Body.Close()
 161  	if resp.StatusCode != http.StatusOK {
 162  		return nil, fmt.Errorf("chunk %s: %d", name, resp.StatusCode)
 163  	}
 164  	return io.ReadAll(resp.Body)
 165  }
 166