filter_source_test.go raw

   1  package neutrino
   2  
   3  import (
   4  	"context"
   5  	"errors"
   6  	"net"
   7  	"testing"
   8  
   9  	"git.smesh.lol/nostrino/pkg/btcwire"
  10  	"git.smesh.lol/nostrino/pkg/chain"
  11  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  12  )
  13  
  14  // filterStore builds a store with headers for 0..len(filters)-1 and the filter
  15  // hashes those filters commit to, which is the state a client is in when it is
  16  // about to fetch filters.
  17  func filterStore(t *testing.T, filters [][]byte) *Memory {
  18  	t.Helper()
  19  
  20  	store := NewMemory()
  21  
  22  	if err := store.SetAnchor(Anchor{Height: 0, BlockHash: chain.Regtest.GenesisHash, FilterHeight: -1}); err != nil {
  23  		t.Fatalf("anchor: %v", err)
  24  	}
  25  
  26  	genesis := chain.Regtest.GenesisHeader
  27  
  28  	if err := store.PutHeaders(0, []btcwire.BlockHeader{genesis}); err != nil {
  29  		t.Fatalf("genesis header: %v", err)
  30  	}
  31  
  32  	prev := genesis.BlockHash()
  33  	headers := make([]btcwire.BlockHeader, 0, len(filters)-1)
  34  
  35  	for i := 1; i < len(filters); i++ {
  36  		header := mine(t, prev, byte(i))
  37  		headers = append(headers, header)
  38  		prev = header.BlockHash()
  39  	}
  40  
  41  	if err := store.PutHeaders(1, headers); err != nil {
  42  		t.Fatalf("headers: %v", err)
  43  	}
  44  
  45  	hashes := make([]chainhash.Hash, len(filters))
  46  	fheaders := make([]chainhash.Hash, len(filters))
  47  	prevFilterHeader := chainhash.Hash{}
  48  
  49  	for i, filter := range filters {
  50  		hashes[i] = chainhash.DoubleHashH(filter)
  51  		fheaders[i] = btcwire.FilterHeader(hashes[i], prevFilterHeader)
  52  		prevFilterHeader = fheaders[i]
  53  	}
  54  
  55  	if err := store.PutFilterHeaders(0, hashes, fheaders); err != nil {
  56  		t.Fatalf("filter headers: %v", err)
  57  	}
  58  
  59  	return store
  60  }
  61  
  62  // testFilters is a deterministic run of filters.
  63  func testFilters(n int) [][]byte {
  64  	out := make([][]byte, n)
  65  
  66  	for i := range out {
  67  		out[i] = []byte{byte(i), byte(i * 7), 0x11, 0x22, 0x33}
  68  	}
  69  
  70  	return out
  71  }
  72  
  73  // clientWithSource is a client whose filters come from a scripted source.
  74  func clientWithSource(t *testing.T, store *Memory, source FilterSource) *Client {
  75  	t.Helper()
  76  
  77  	client, err := New(Config{
  78  		Profile: &chain.Regtest,
  79  		Store:   store,
  80  		Dial:    func(context.Context) (net.Conn, error) { return nil, errors.New("no peer") },
  81  	})
  82  
  83  	if err != nil {
  84  		t.Fatal(err)
  85  	}
  86  
  87  	client.cfg.FilterSource = source
  88  
  89  	return client
  90  }
  91  
  92  // TestSourceStoresWhatItVerifies: a run the source supplies is stored, and the
  93  // store's filter tip advances to its end.
  94  func TestSourceStoresWhatItVerifies(t *testing.T) {
  95  	filters := testFilters(11)
  96  	store := filterStore(t, filters)
  97  	client := clientWithSource(t, store, func(_ context.Context, from, to uint32) ([]Filters, error) {
  98  		if from != 1 || to != 5 {
  99  			t.Fatalf("source asked for %d..%d, want 1..5", from, to)
 100  		}
 101  
 102  		return []Filters{{From: 1, Filters: filters[1:6]}}, nil
 103  	})
 104  
 105  	served, bytes := client.fromSource(context.Background(), 1, 5)
 106  
 107  	if served != 5 {
 108  		t.Fatalf("stored %d filters, want 5", served)
 109  	}
 110  
 111  	if bytes != 25 {
 112  		t.Fatalf("stored %d bytes, want 25", bytes)
 113  	}
 114  
 115  	if tip, ok := store.FilterTip(); !ok || tip != 5 {
 116  		t.Fatalf("filter tip is %d (ok=%v), want 5", tip, ok)
 117  	}
 118  }
 119  
 120  // TestSourceStopsAtAWrongFilter: a filter that does not hash to the commitment
 121  // is not stored, and neither is anything above it. The peer then fetches from
 122  // that height, which is the whole point of the fallback.
 123  func TestSourceStopsAtAWrongFilter(t *testing.T) {
 124  	filters := testFilters(11)
 125  	store := filterStore(t, filters)
 126  
 127  	bad := append([][]byte{}, filters[:6]...)
 128  	bad[4] = []byte{0xde, 0xad, 0xbe, 0xef}
 129  
 130  	client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) {
 131  		return []Filters{{From: 1, Filters: bad[1:6]}}, nil
 132  	})
 133  
 134  	served, _ := client.fromSource(context.Background(), 1, 5)
 135  
 136  	if served != 3 {
 137  		t.Fatalf("stored %d filters before the wrong one, want 3", served)
 138  	}
 139  
 140  	// The tip must not move past the hole: a tip above a missing filter makes
 141  	// the next sync start above it and the block is never scanned.
 142  	if tip, ok := store.FilterTip(); !ok || tip != 3 {
 143  		t.Fatalf("filter tip is %d (ok=%v), want 3", tip, ok)
 144  	}
 145  
 146  	if _, ok := store.Filter(4); ok {
 147  		t.Fatal("the filter above the wrong one was stored")
 148  	}
 149  }
 150  
 151  // TestSourceRunMustStartAtTheHeight: a run that begins above the height the
 152  // client needs leaves nothing to store, because the height in between is still
 153  // missing and the peer has to fill it.
 154  func TestSourceRunMustStartAtTheHeight(t *testing.T) {
 155  	filters := testFilters(11)
 156  	store := filterStore(t, filters)
 157  	client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) {
 158  		return []Filters{{From: 3, Filters: filters[3:6]}}, nil
 159  	})
 160  
 161  	if served, _ := client.fromSource(context.Background(), 1, 5); served != 0 {
 162  		t.Fatalf("stored %d filters from a run that starts above the request", served)
 163  	}
 164  }
 165  
 166  // TestSourceTakesRunsInOrder: the relay answers with the batches it holds, so
 167  // several runs arrive for one window. Each has to be consumed in turn.
 168  func TestSourceTakesRunsInOrder(t *testing.T) {
 169  	filters := testFilters(11)
 170  	store := filterStore(t, filters)
 171  	client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) {
 172  		return []Filters{
 173  			{From: 1, Filters: filters[1:3]},
 174  			{From: 3, Filters: filters[3:5]},
 175  			{From: 5, Filters: filters[5:6]},
 176  		}, nil
 177  	})
 178  
 179  	served, _ := client.fromSource(context.Background(), 1, 5)
 180  
 181  	if served != 5 {
 182  		t.Fatalf("stored %d filters across three runs, want 5", served)
 183  	}
 184  
 185  	if tip, ok := store.FilterTip(); !ok || tip != 5 {
 186  		t.Fatalf("filter tip is %d (ok=%v), want 5", tip, ok)
 187  	}
 188  }
 189  
 190  // TestSourceEmptyIsNotAnError: a cache with no coverage is the normal case, and
 191  // it must behave exactly like no source at all.
 192  func TestSourceEmptyIsNotAnError(t *testing.T) {
 193  	filters := testFilters(11)
 194  	store := filterStore(t, filters)
 195  	client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) {
 196  		return nil, nil
 197  	})
 198  
 199  	if served, _ := client.fromSource(context.Background(), 1, 5); served != 0 {
 200  		t.Fatalf("stored %d filters from an empty source", served)
 201  	}
 202  
 203  	if _, ok := store.FilterTip(); ok {
 204  		t.Fatal("an empty source moved the filter tip")
 205  	}
 206  }
 207  
 208  // TestSourceFailureIsNotASyncFailure: an unreachable relay costs the range, not
 209  // the scan.
 210  func TestSourceFailureIsNotASyncFailure(t *testing.T) {
 211  	filters := testFilters(11)
 212  	store := filterStore(t, filters)
 213  	client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) {
 214  		return nil, errors.New("relay unreachable")
 215  	})
 216  
 217  	if served, _ := client.fromSource(context.Background(), 1, 5); served != 0 {
 218  		t.Fatalf("stored %d filters after a source failure", served)
 219  	}
 220  }
 221  
 222  // TestSyncFiltersNeedsNoPeerWhenTheSourceHasItAll: a cache that covers the
 223  // range means the gateway is never dialed. That is what makes the cache a
 224  // substitute for the peer rather than a decoration in front of it.
 225  func TestSyncFiltersNeedsNoPeerWhenTheSourceHasItAll(t *testing.T) {
 226  	filters := testFilters(21)
 227  	store := filterStore(t, filters)
 228  
 229  	dialed := 0
 230  
 231  	client, err := New(Config{
 232  		Profile: &chain.Regtest,
 233  		Store:   store,
 234  		Dial: func(context.Context) (net.Conn, error) {
 235  			dialed++
 236  
 237  			return nil, errors.New("no peer")
 238  		},
 239  	})
 240  	if err != nil {
 241  		t.Fatal(err)
 242  	}
 243  
 244  	client.cfg.FilterSource = func(_ context.Context, from, to uint32) ([]Filters, error) {
 245  		return []Filters{{From: from, Filters: filters[from : to+1]}}, nil
 246  	}
 247  
 248  	stored, _, err := client.SyncFilters(context.Background(), 1, 0)
 249  	if err != nil {
 250  		t.Fatalf("sync: %v", err)
 251  	}
 252  
 253  	if stored != 20 {
 254  		t.Fatalf("stored %d filters, want 20", stored)
 255  	}
 256  
 257  	if tip, ok := store.FilterTip(); !ok || tip != 20 {
 258  		t.Fatalf("filter tip is %d (ok=%v), want 20", tip, ok)
 259  	}
 260  
 261  	if dialed != 0 {
 262  		t.Fatalf("the peer was dialed %d times for a range the cache covered", dialed)
 263  	}
 264  }
 265  
 266  // TestSyncFiltersDialsWhenTheSourceIsEmpty: the peer is late, not gone. A cache
 267  // with nothing must still produce a dial, or a range with no coverage would end
 268  // as an empty success.
 269  func TestSyncFiltersDialsWhenTheSourceIsEmpty(t *testing.T) {
 270  	filters := testFilters(21)
 271  	store := filterStore(t, filters)
 272  
 273  	dialed := 0
 274  
 275  	client, err := New(Config{
 276  		Profile: &chain.Regtest,
 277  		Store:   store,
 278  		Dial: func(context.Context) (net.Conn, error) {
 279  			dialed++
 280  
 281  			return nil, errors.New("no peer")
 282  		},
 283  	})
 284  	if err != nil {
 285  		t.Fatal(err)
 286  	}
 287  
 288  	client.cfg.FilterSource = func(context.Context, uint32, uint32) ([]Filters, error) {
 289  		return nil, nil
 290  	}
 291  
 292  	if _, _, err := client.SyncFilters(context.Background(), 1, 0); err == nil {
 293  		t.Fatal("an uncovered range with no peer was reported as success")
 294  	}
 295  
 296  	if dialed != 1 {
 297  		t.Fatalf("the peer was dialed %d times, want 1", dialed)
 298  	}
 299  }
 300  
 301  // TestWindowFollowsTheFilterSize: the window is a byte budget, so a chain of
 302  // small filters is asked for in wide windows and a chain of large ones in narrow
 303  // ones. Measured: 5,014 fork blocks in 51 requests of about 213 KB each is a
 304  // latency-bound scan, while the same count of Bitcoin blocks is bandwidth-bound.
 305  func TestWindowFollowsTheFilterSize(t *testing.T) {
 306  	cases := []struct {
 307  		name    string
 308  		size    int
 309  		want    uint32
 310  		heights int
 311  	}{
 312  		{"small filters widen the window", 2_500, SourceMaxWindow, 1_000},
 313  		{"large filters keep it narrow", 20_000, 104, 500},
 314  	}
 315  
 316  	for _, tc := range cases {
 317  		t.Run(tc.name, func(t *testing.T) {
 318  			filters := make([][]byte, tc.heights)
 319  			for i := range filters {
 320  				filters[i] = make([]byte, tc.size)
 321  				filters[i][0] = byte(i)
 322  				filters[i][1] = byte(i >> 8)
 323  			}
 324  
 325  			store := filterStore(t, filters)
 326  
 327  			var spans []uint32
 328  
 329  			client := clientWithSource(t, store, func(_ context.Context, from, to uint32) ([]Filters, error) {
 330  				spans = append(spans, to-from+1)
 331  
 332  				return []Filters{{From: from, Filters: filters[from : to+1]}}, nil
 333  			})
 334  
 335  			if _, _, err := client.SyncFilters(context.Background(), 1, 0); err != nil {
 336  				t.Fatalf("sync: %v", err)
 337  			}
 338  
 339  			if len(spans) < 2 {
 340  				t.Fatalf("only %d windows were asked for", len(spans))
 341  			}
 342  
 343  			if spans[0] != filterSourceWindow {
 344  				t.Fatalf("the first window is %d, want %d", spans[0], filterSourceWindow)
 345  			}
 346  
 347  			if spans[1] != tc.want {
 348  				t.Fatalf("the second window is %d, want %d", spans[1], tc.want)
 349  			}
 350  		})
 351  	}
 352  }
 353  
 354  // TestSourceWindowIsBounded: the client asks for a window, not for a whole
 355  // scan. Without that bound one call holds the filters of a thousand blocks.
 356  func TestSourceWindowIsBounded(t *testing.T) {
 357  	filters := testFilters(400)
 358  	store := filterStore(t, filters)
 359  
 360  	var asked []uint32
 361  
 362  	client := clientWithSource(t, store, func(_ context.Context, from, to uint32) ([]Filters, error) {
 363  		asked = append(asked, to-from+1)
 364  
 365  		return nil, nil
 366  	})
 367  
 368  	if filterSourceWindow != 100 {
 369  		t.Fatalf("the window is %d", filterSourceWindow)
 370  	}
 371  
 372  	// One call with the range the sync loop would cut, bounded by the window.
 373  	window := uint32(1) + filterSourceWindow - 1
 374  
 375  	if served, _ := client.fromSource(context.Background(), 1, window); served != 0 {
 376  		t.Fatalf("stored %d filters from an empty source", served)
 377  	}
 378  
 379  	if len(asked) != 1 || asked[0] != filterSourceWindow {
 380  		t.Fatalf("asked for windows %v, want one of %d", asked, filterSourceWindow)
 381  	}
 382  }
 383