pool_test.go raw

   1  package filler
   2  
   3  import (
   4  	"context"
   5  	"encoding/binary"
   6  	"fmt"
   7  	"path/filepath"
   8  	"strings"
   9  	"sync"
  10  	"testing"
  11  	"time"
  12  
  13  	"git.smesh.lol/nostrino/pkg/btcwire"
  14  	"git.smesh.lol/nostrino/pkg/neutrino"
  15  
  16  	"git.smesh.lol/btcd-lite/internal/chains"
  17  
  18  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  19  
  20  	"git.smesh.lol/btcd-lite/internal/staging"
  21  	"git.smesh.lol/btcd-lite/internal/store"
  22  	"git.smesh.lol/btcd-lite/internal/v2peer"
  23  )
  24  
  25  // TestAcceptStagesWithoutHashing: the pool writes what a peer sent to the
  26  // staging log under the claim it asked for. It does not hash the bytes and it
  27  // does not touch the body store: both are the processing pass's work, and the
  28  // refusals that follow from them are tested there.
  29  func TestAcceptStagesWithoutHashing(t *testing.T) {
  30  	dir := t.TempDir()
  31  	bodies, err := store.NewBlockStore(filepath.Join(dir, "blocks"))
  32  	if err != nil {
  33  		t.Fatal(err)
  34  	}
  35  	defer bodies.Close()
  36  	log, err := staging.Open(filepath.Join(dir, "staging"))
  37  	if err != nil {
  38  		t.Fatal(err)
  39  	}
  40  	defer log.Close()
  41  	p := &Pool{cfg: PoolConfig{Bodies: bodies, Staging: log}}
  42  	var want chainhash.Hash
  43  	want[0] = 1
  44  	raw := make([]byte, 96)
  45  	binary.LittleEndian.PutUint32(raw[0:4], 1)
  46  	for i := 80; i < len(raw); i++ {
  47  		raw[i] = byte(i)
  48  	}
  49  	if err := p.accept(5, want, raw); err != nil {
  50  		t.Fatalf("a body was refused at the download: %v", err)
  51  	}
  52  	if !log.Has(5) {
  53  		t.Fatal("the body was not staged")
  54  	}
  55  	if bodies.Len() != 0 {
  56  		t.Fatalf("the pool wrote %d blocks into the store", bodies.Len())
  57  	}
  58  	// A body shorter than a header cannot be one, and is refused before it is
  59  	// written.
  60  	if err := p.accept(6, want, []byte{1, 2, 3}); err == nil {
  61  		t.Fatal("a 3-byte body was staged")
  62  	}
  63  }
  64  
  65  // TestNotFoundIsReported: a peer that does not have a block is an error, not an
  66  // empty block.
  67  func TestNotFoundIsReported(t *testing.T) {
  68  	if v2peer.ErrNotFound == nil {
  69  		t.Fatal("no not-found error")
  70  	}
  71  }
  72  
  73  // TestNextHandsOutEachHeightOnce: four workers pulling at the same time never
  74  // get the same height twice and between them get every height, which is what
  75  // one request in flight per peer needs from the bookkeeping.
  76  func TestNextHandsOutEachHeightOnce(t *testing.T) {
  77  	const heights = 500
  78  	dir := t.TempDir()
  79  	headers, err := store.NewHeaderStore(filepath.Join(dir, "headers"))
  80  	if err != nil {
  81  		t.Fatal(err)
  82  	}
  83  	defer headers.Close()
  84  	hdrs := make([]btcwire.BlockHeader, 0, heights)
  85  	for i := 0; i < heights; i++ {
  86  		hdrs = append(hdrs, btcwire.BlockHeader{Version: 1, Nonce: uint32(i), Timestamp: 1231006505 + uint32(i)})
  87  	}
  88  	if err := headers.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil {
  89  		t.Fatal(err)
  90  	}
  91  	if err := headers.PutHeaders(0, hdrs); err != nil {
  92  		t.Fatal(err)
  93  	}
  94  	bodies, err := store.NewBlockStore(filepath.Join(dir, "blocks"))
  95  	if err != nil {
  96  		t.Fatal(err)
  97  	}
  98  	defer bodies.Close()
  99  	staged, err := staging.Open(filepath.Join(dir, "staging"))
 100  	if err != nil {
 101  		t.Fatal(err)
 102  	}
 103  	defer staged.Close()
 104  	p, err := NewPool(PoolConfig{
 105  		Profile: chains.Regtest().Profile, Headers: headers, Bodies: bodies, Staging: staged,
 106  		Peers: []Peer{{Addr: "a"}, {Addr: "b"}, {Addr: "c"}, {Addr: "d"}},
 107  	})
 108  	if err != nil {
 109  		t.Fatal(err)
 110  	}
 111  	p.target.Store(heights)
 112  	var mu sync.Mutex
 113  	seen := map[uint32]int{}
 114  	var wg sync.WaitGroup
 115  	for i := 0; i < 4; i++ {
 116  		wg.Add(1)
 117  		go func() {
 118  			defer wg.Done()
 119  			for {
 120  				h, ok := p.next()
 121  				if !ok {
 122  					return
 123  				}
 124  				mu.Lock()
 125  				seen[h]++
 126  				mu.Unlock()
 127  				p.complete(h)
 128  			}
 129  		}()
 130  	}
 131  	wg.Wait()
 132  	if len(seen) != heights {
 133  		t.Fatalf("%d of %d heights were handed out", len(seen), heights)
 134  	}
 135  	for h, n := range seen {
 136  		if n != 1 {
 137  			t.Fatalf("height %d was handed out %d times", h, n)
 138  		}
 139  	}
 140  }
 141  
 142  // TestProgressLine: the line a fill writes on its timer carries the count, the
 143  // percentage, the rate and an estimate, and it appears even when nothing has
 144  // completed, which is the case that matters when a fill has stalled.
 145  func TestProgressLine(t *testing.T) {
 146  	var mu sync.Mutex
 147  	var lines []string
 148  	p := &Pool{cfg: PoolConfig{
 149  		ProgressEvery: 5 * time.Millisecond,
 150  		Logf: func(f string, a ...any) {
 151  			mu.Lock()
 152  			lines = append(lines, fmt.Sprintf(f, a...))
 153  			mu.Unlock()
 154  		},
 155  	}}
 156  	p.target.Store(1000)
 157  	p.stored = map[uint32]bool{0: true, 1: true}
 158  	p.claimed = map[uint32]bool{}
 159  	p.reuse = map[string]*conn{}
 160  	stop := make(chan struct{})
 161  	done := make(chan struct{})
 162  	go func() { p.progressLoop(context.Background(), stop); close(done) }()
 163  	// Let one line go by with nothing completing.
 164  	time.Sleep(30 * time.Millisecond)
 165  	p.done.Store(20)
 166  	time.Sleep(30 * time.Millisecond)
 167  	close(stop)
 168  	<-done
 169  	mu.Lock()
 170  	defer mu.Unlock()
 171  	if len(lines) == 0 {
 172  		t.Fatal("no progress line")
 173  	}
 174  	first := lines[0]
 175  	if !strings.Contains(first, "2/1000") || !strings.Contains(first, "(0.2%)") {
 176  		t.Fatalf("the first line does not carry the count and the percentage: %q", first)
 177  	}
 178  	if !strings.Contains(first, "eta never") {
 179  		t.Fatalf("a stalled fill did not say never: %q", first)
 180  	}
 181  	found := false
 182  	for _, l := range lines[1:] {
 183  		if strings.Contains(l, "blocks/s") && !strings.Contains(l, "eta never") {
 184  			found = true
 185  			break
 186  		}
 187  	}
 188  	if !found {
 189  		t.Fatalf("no line carried a rate and an estimate:\n%s", strings.Join(lines, "\n"))
 190  	}
 191  }
 192