package neutrino import ( "context" "errors" "net" "testing" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // filterStore builds a store with headers for 0..len(filters)-1 and the filter // hashes those filters commit to, which is the state a client is in when it is // about to fetch filters. func filterStore(t *testing.T, filters [][]byte) *Memory { t.Helper() store := NewMemory() if err := store.SetAnchor(Anchor{Height: 0, BlockHash: chain.Regtest.GenesisHash, FilterHeight: -1}); err != nil { t.Fatalf("anchor: %v", err) } genesis := chain.Regtest.GenesisHeader if err := store.PutHeaders(0, []btcwire.BlockHeader{genesis}); err != nil { t.Fatalf("genesis header: %v", err) } prev := genesis.BlockHash() headers := make([]btcwire.BlockHeader, 0, len(filters)-1) for i := 1; i < len(filters); i++ { header := mine(t, prev, byte(i)) headers = append(headers, header) prev = header.BlockHash() } if err := store.PutHeaders(1, headers); err != nil { t.Fatalf("headers: %v", err) } hashes := make([]chainhash.Hash, len(filters)) fheaders := make([]chainhash.Hash, len(filters)) prevFilterHeader := chainhash.Hash{} for i, filter := range filters { hashes[i] = chainhash.DoubleHashH(filter) fheaders[i] = btcwire.FilterHeader(hashes[i], prevFilterHeader) prevFilterHeader = fheaders[i] } if err := store.PutFilterHeaders(0, hashes, fheaders); err != nil { t.Fatalf("filter headers: %v", err) } return store } // testFilters is a deterministic run of filters. func testFilters(n int) [][]byte { out := make([][]byte, n) for i := range out { out[i] = []byte{byte(i), byte(i * 7), 0x11, 0x22, 0x33} } return out } // clientWithSource is a client whose filters come from a scripted source. func clientWithSource(t *testing.T, store *Memory, source FilterSource) *Client { t.Helper() client, err := New(Config{ Profile: &chain.Regtest, Store: store, Dial: func(context.Context) (net.Conn, error) { return nil, errors.New("no peer") }, }) if err != nil { t.Fatal(err) } client.cfg.FilterSource = source return client } // TestSourceStoresWhatItVerifies: a run the source supplies is stored, and the // store's filter tip advances to its end. func TestSourceStoresWhatItVerifies(t *testing.T) { filters := testFilters(11) store := filterStore(t, filters) client := clientWithSource(t, store, func(_ context.Context, from, to uint32) ([]Filters, error) { if from != 1 || to != 5 { t.Fatalf("source asked for %d..%d, want 1..5", from, to) } return []Filters{{From: 1, Filters: filters[1:6]}}, nil }) served, bytes := client.fromSource(context.Background(), 1, 5) if served != 5 { t.Fatalf("stored %d filters, want 5", served) } if bytes != 25 { t.Fatalf("stored %d bytes, want 25", bytes) } if tip, ok := store.FilterTip(); !ok || tip != 5 { t.Fatalf("filter tip is %d (ok=%v), want 5", tip, ok) } } // TestSourceStopsAtAWrongFilter: a filter that does not hash to the commitment // is not stored, and neither is anything above it. The peer then fetches from // that height, which is the whole point of the fallback. func TestSourceStopsAtAWrongFilter(t *testing.T) { filters := testFilters(11) store := filterStore(t, filters) bad := append([][]byte{}, filters[:6]...) bad[4] = []byte{0xde, 0xad, 0xbe, 0xef} client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) { return []Filters{{From: 1, Filters: bad[1:6]}}, nil }) served, _ := client.fromSource(context.Background(), 1, 5) if served != 3 { t.Fatalf("stored %d filters before the wrong one, want 3", served) } // The tip must not move past the hole: a tip above a missing filter makes // the next sync start above it and the block is never scanned. if tip, ok := store.FilterTip(); !ok || tip != 3 { t.Fatalf("filter tip is %d (ok=%v), want 3", tip, ok) } if _, ok := store.Filter(4); ok { t.Fatal("the filter above the wrong one was stored") } } // TestSourceRunMustStartAtTheHeight: a run that begins above the height the // client needs leaves nothing to store, because the height in between is still // missing and the peer has to fill it. func TestSourceRunMustStartAtTheHeight(t *testing.T) { filters := testFilters(11) store := filterStore(t, filters) client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) { return []Filters{{From: 3, Filters: filters[3:6]}}, nil }) if served, _ := client.fromSource(context.Background(), 1, 5); served != 0 { t.Fatalf("stored %d filters from a run that starts above the request", served) } } // TestSourceTakesRunsInOrder: the relay answers with the batches it holds, so // several runs arrive for one window. Each has to be consumed in turn. func TestSourceTakesRunsInOrder(t *testing.T) { filters := testFilters(11) store := filterStore(t, filters) client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) { return []Filters{ {From: 1, Filters: filters[1:3]}, {From: 3, Filters: filters[3:5]}, {From: 5, Filters: filters[5:6]}, }, nil }) served, _ := client.fromSource(context.Background(), 1, 5) if served != 5 { t.Fatalf("stored %d filters across three runs, want 5", served) } if tip, ok := store.FilterTip(); !ok || tip != 5 { t.Fatalf("filter tip is %d (ok=%v), want 5", tip, ok) } } // TestSourceEmptyIsNotAnError: a cache with no coverage is the normal case, and // it must behave exactly like no source at all. func TestSourceEmptyIsNotAnError(t *testing.T) { filters := testFilters(11) store := filterStore(t, filters) client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) { return nil, nil }) if served, _ := client.fromSource(context.Background(), 1, 5); served != 0 { t.Fatalf("stored %d filters from an empty source", served) } if _, ok := store.FilterTip(); ok { t.Fatal("an empty source moved the filter tip") } } // TestSourceFailureIsNotASyncFailure: an unreachable relay costs the range, not // the scan. func TestSourceFailureIsNotASyncFailure(t *testing.T) { filters := testFilters(11) store := filterStore(t, filters) client := clientWithSource(t, store, func(context.Context, uint32, uint32) ([]Filters, error) { return nil, errors.New("relay unreachable") }) if served, _ := client.fromSource(context.Background(), 1, 5); served != 0 { t.Fatalf("stored %d filters after a source failure", served) } } // TestSyncFiltersNeedsNoPeerWhenTheSourceHasItAll: a cache that covers the // range means the gateway is never dialed. That is what makes the cache a // substitute for the peer rather than a decoration in front of it. func TestSyncFiltersNeedsNoPeerWhenTheSourceHasItAll(t *testing.T) { filters := testFilters(21) store := filterStore(t, filters) dialed := 0 client, err := New(Config{ Profile: &chain.Regtest, Store: store, Dial: func(context.Context) (net.Conn, error) { dialed++ return nil, errors.New("no peer") }, }) if err != nil { t.Fatal(err) } client.cfg.FilterSource = func(_ context.Context, from, to uint32) ([]Filters, error) { return []Filters{{From: from, Filters: filters[from : to+1]}}, nil } stored, _, err := client.SyncFilters(context.Background(), 1, 0) if err != nil { t.Fatalf("sync: %v", err) } if stored != 20 { t.Fatalf("stored %d filters, want 20", stored) } if tip, ok := store.FilterTip(); !ok || tip != 20 { t.Fatalf("filter tip is %d (ok=%v), want 20", tip, ok) } if dialed != 0 { t.Fatalf("the peer was dialed %d times for a range the cache covered", dialed) } } // TestSyncFiltersDialsWhenTheSourceIsEmpty: the peer is late, not gone. A cache // with nothing must still produce a dial, or a range with no coverage would end // as an empty success. func TestSyncFiltersDialsWhenTheSourceIsEmpty(t *testing.T) { filters := testFilters(21) store := filterStore(t, filters) dialed := 0 client, err := New(Config{ Profile: &chain.Regtest, Store: store, Dial: func(context.Context) (net.Conn, error) { dialed++ return nil, errors.New("no peer") }, }) if err != nil { t.Fatal(err) } client.cfg.FilterSource = func(context.Context, uint32, uint32) ([]Filters, error) { return nil, nil } if _, _, err := client.SyncFilters(context.Background(), 1, 0); err == nil { t.Fatal("an uncovered range with no peer was reported as success") } if dialed != 1 { t.Fatalf("the peer was dialed %d times, want 1", dialed) } } // TestWindowFollowsTheFilterSize: the window is a byte budget, so a chain of // small filters is asked for in wide windows and a chain of large ones in narrow // ones. Measured: 5,014 fork blocks in 51 requests of about 213 KB each is a // latency-bound scan, while the same count of Bitcoin blocks is bandwidth-bound. func TestWindowFollowsTheFilterSize(t *testing.T) { cases := []struct { name string size int want uint32 heights int }{ {"small filters widen the window", 2_500, SourceMaxWindow, 1_000}, {"large filters keep it narrow", 20_000, 104, 500}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { filters := make([][]byte, tc.heights) for i := range filters { filters[i] = make([]byte, tc.size) filters[i][0] = byte(i) filters[i][1] = byte(i >> 8) } store := filterStore(t, filters) var spans []uint32 client := clientWithSource(t, store, func(_ context.Context, from, to uint32) ([]Filters, error) { spans = append(spans, to-from+1) return []Filters{{From: from, Filters: filters[from : to+1]}}, nil }) if _, _, err := client.SyncFilters(context.Background(), 1, 0); err != nil { t.Fatalf("sync: %v", err) } if len(spans) < 2 { t.Fatalf("only %d windows were asked for", len(spans)) } if spans[0] != filterSourceWindow { t.Fatalf("the first window is %d, want %d", spans[0], filterSourceWindow) } if spans[1] != tc.want { t.Fatalf("the second window is %d, want %d", spans[1], tc.want) } }) } } // TestSourceWindowIsBounded: the client asks for a window, not for a whole // scan. Without that bound one call holds the filters of a thousand blocks. func TestSourceWindowIsBounded(t *testing.T) { filters := testFilters(400) store := filterStore(t, filters) var asked []uint32 client := clientWithSource(t, store, func(_ context.Context, from, to uint32) ([]Filters, error) { asked = append(asked, to-from+1) return nil, nil }) if filterSourceWindow != 100 { t.Fatalf("the window is %d", filterSourceWindow) } // One call with the range the sync loop would cut, bounded by the window. window := uint32(1) + filterSourceWindow - 1 if served, _ := client.fromSource(context.Background(), 1, window); served != 0 { t.Fatalf("stored %d filters from an empty source", served) } if len(asked) != 1 || asked[0] != filterSourceWindow { t.Fatalf("asked for windows %v, want one of %d", asked, filterSourceWindow) } }