package domain import ( "context" "fmt" "sort" "git.smesh.lol/tinywallet/pkg/scanner" ) // ScanBackwards is the wallet-driven scan: filters from the verified tip downwards, stopping at // the wallet's floor or after a gap of blocks with no match. // // Headers and filter headers are not downloaded here. That is the chain's job, done forward in the // background before a seed exists. This only spends bandwidth on filters the wallet's scripts can // use, newest first, because a wallet's spendable coins are recent far more often than not. func (d *Domain) ScanBackwards(ctx context.Context, name string, window, gap uint32) (Report, error) { link, err := d.link(name) if err != nil { return Report{}, err } derived, err := d.walletOf(name) if err != nil { return Report{}, err } meta, err := d.meta(name) if err != nil { return Report{}, err } scripts, err := d.scanScripts(name, derived, meta, DefaultLookahead) if err != nil { return Report{}, err } position, err := link.Client.Position() if err != nil { return Report{}, fmt.Errorf("domain: %q: position: %w", name, err) } report := Report{Chain: name, Scripts: len(scripts)} adapter := &scanChain{link: link, scripts: scripts} result, err := scanner.Backwards(ctx, adapter, scripts, scanner.Options{ Floor: meta.FilterFrom, Window: window, Gap: gap, OnMatch: func(ctx context.Context, height uint32) error { raw, err := link.Client.Block(height) if err != nil { return fmt.Errorf("domain: %q: block %d: %w", name, height, err) } if _, err := d.scanBlock(derived, raw, height); err != nil { return fmt.Errorf("domain: %q: scanning block %d: %w", name, height, err) } return nil }, }) report.Matched = append([]uint32{}, result.Matched...) sort.Slice(report.Matched, func(i, j int) bool { return report.Matched[i] < report.Matched[j] }) report.New = report.Matched report.From = result.Lowest report.Position = position return report, err } // scanChain adapts one chain's client to what a backwards walk needs. type scanChain struct { link Link scripts [][]byte } func (s *scanChain) Tip(context.Context) (uint32, error) { position, err := s.link.Client.Position() if err != nil { return 0, err } return position.Tip, nil } // Fetch downloads one window. The walk asks for ascending ranges, so the client is given exactly // that and nothing wider. func (s *scanChain) Fetch(ctx context.Context, from, to uint32) error { return s.link.Client.FetchFilters(from, to) } // Match returns the window's matches. The chain's matcher covers everything it has stored, so the // result is narrowed to the window: a match outside it belongs to another window of the walk. func (s *scanChain) Match(_ context.Context, from, to uint32, _ [][]byte) ([]uint32, error) { heights, err := s.link.Client.Match(s.scripts) if err != nil { return nil, err } out := make([]uint32, 0, len(heights)) for _, height := range heights { if height >= from && height <= to { out = append(out, height) } } return out, nil }