package scanner import ( "context" "errors" "testing" ) // fakeChain records the windows it was asked for, which is the behaviour under test: the walk // must be a descending series of ascending windows, never one huge range. type fakeChain struct { tip uint32 windows [][2]uint32 matches map[uint32]bool failAt uint32 } func (f *fakeChain) Tip(context.Context) (uint32, error) { return f.tip, nil } func (f *fakeChain) Fetch(_ context.Context, from, to uint32) error { f.windows = append(f.windows, [2]uint32{from, to}) if f.failAt != 0 && to == f.failAt { return errors.New("peer disconnected") } return nil } func (f *fakeChain) Match(_ context.Context, from, to uint32, _ [][]byte) ([]uint32, error) { var out []uint32 for height := from; height <= to; height++ { if f.matches[height] { out = append(out, height) } } return out, nil } // TestTheWalkGoesBackwardsInAscendingWindows: a node serves ascending ranges, so a backwards walk // is a series of them, newest first, and every window is within the protocol limit. func TestTheWalkGoesBackwardsInAscendingWindows(t *testing.T) { chain := &fakeChain{tip: 2000, matches: map[uint32]bool{1700: true}} result, err := Backwards(context.Background(), chain, [][]byte{{1}}, Options{Window: 500, Gap: 600}) if err != nil { t.Fatal(err) } if len(result.Matched) != 1 || result.Matched[0] != 1700 { t.Fatalf("matched %v", result.Matched) } want := [][2]uint32{{1501, 2000}, {1001, 1500}, {501, 1000}} if len(chain.windows) != len(want) { t.Fatalf("windows %v, want %v", chain.windows, want) } for i, window := range want { if chain.windows[i] != window { t.Fatalf("window %d is %v, want %v", i, chain.windows[i], window) } if chain.windows[i][1]-chain.windows[i][0] >= 1000 { t.Fatalf("window %v spans more than the node allows", chain.windows[i]) } } if result.Stopped != "gap" { t.Fatalf("stopped by %q, want gap", result.Stopped) } } // TestTheWalkStopsAtItsFloor: a wallet with a known birthday never scans below it. func TestTheWalkStopsAtItsFloor(t *testing.T) { chain := &fakeChain{tip: 1200, matches: map[uint32]bool{}} result, err := Backwards(context.Background(), chain, [][]byte{{1}}, Options{Window: 500, Floor: 800, Gap: 1 << 20}) if err != nil { t.Fatal(err) } if result.Stopped != "floor" || result.Lowest != 800 { t.Fatalf("stopped %q at %d", result.Stopped, result.Lowest) } } // TestAFailedWindowIsAnError: the walk reports the window it could not fetch rather than silently // skipping history. func TestAFailedWindowIsAnError(t *testing.T) { chain := &fakeChain{tip: 2000, matches: map[uint32]bool{}, failAt: 1000} if _, err := Backwards(context.Background(), chain, [][]byte{{1}}, Options{Window: 500, Gap: 1 << 20}); err == nil { t.Fatal("a failed fetch was not reported") } }