scanner.go raw

   1  // Package scanner walks a chain's compact filters backwards from the tip.
   2  //
   3  // A wallet usually does not know its history, and it does not need to: the coins it can spend are
   4  // recent far more often than not. So the useful order is newest first, stopping once the scan has
   5  // passed the wallet's activity, and the useful unit is a window — BIP157 ranges ascend, so a
   6  // backwards walk is a descending series of ascending windows.
   7  //
   8  // Headers and filter headers are not this package's business: they are verified forward once, in
   9  // the background, and give every window a chain to stand on.
  10  package scanner
  11  
  12  import (
  13  	"context"
  14  	"errors"
  15  	"fmt"
  16  )
  17  
  18  // ErrNoTip is a chain that has not synced far enough to scan.
  19  var ErrNoTip = errors.New("scanner: the chain has no verified tip")
  20  
  21  // Chain is what a backwards walk needs from a light client.
  22  type Chain interface {
  23  	// Tip is the highest height whose filter header is verified.
  24  	Tip(ctx context.Context) (uint32, error)
  25  	// Fetch downloads and verifies the filters for [from, to], inclusive. It may be asked for
  26  	// the same window twice after a failure; it must be idempotent.
  27  	Fetch(ctx context.Context, from, to uint32) error
  28  	// Match returns the heights in [from, to] whose filters mention one of the scripts.
  29  	Match(ctx context.Context, from, to uint32, scripts [][]byte) ([]uint32, error)
  30  }
  31  
  32  // Options bounds a walk.
  33  type Options struct {
  34  	// Floor is the lowest height to scan, usually the wallet's birthday or a chain checkpoint.
  35  	// Zero means the walk may go to genesis.
  36  	Floor uint32
  37  	// Window is how many blocks one fetch covers. Zero means 500.
  38  	Window uint32
  39  	// Gap is how many consecutive blocks whose filters do not mention any of the wallet's scripts
  40  	// end the walk: the point where the wallet's activity has clearly been passed. It is not
  41  	// about empty blocks — every block has a coinbase — but about blocks with nothing for these
  42  	// keys. Zero means no gap stop, which is what a full rescan wants.
  43  	Gap uint32
  44  	// OnMatch receives each matched height, in descending discovery order.
  45  	OnMatch func(ctx context.Context, height uint32) error
  46  }
  47  
  48  // Result is what a walk covered.
  49  type Result struct {
  50  	// Scanned is how many blocks were fetched and examined.
  51  	Scanned uint32
  52  	// Lowest is the lowest height reached.
  53  	Lowest uint32
  54  	// Matched is every matching height found, newest first.
  55  	Matched []uint32
  56  	// Stopped says why: "floor", "gap" or "tip".
  57  	Stopped string
  58  }
  59  
  60  // Backwards walks from the tip down to the floor, or until a gap of blocks with no match.
  61  //
  62  // The walk is chunked on purpose: a single BIP157 request cannot span more than a thousand blocks,
  63  // and asking for the whole range would be one enormous request the node disconnects for. Each
  64  // window is fetched ascending, then examined, and the next window starts below it.
  65  func Backwards(ctx context.Context, chain Chain, scripts [][]byte, opts Options) (Result, error) {
  66  	var result Result
  67  
  68  	if opts.Window == 0 {
  69  		opts.Window = 500
  70  	}
  71  
  72  	if len(scripts) == 0 {
  73  		return result, errors.New("scanner: no scripts to look for")
  74  	}
  75  
  76  	tip, err := chain.Tip(ctx)
  77  
  78  	if err != nil {
  79  		return result, err
  80  	}
  81  
  82  	if tip == 0 {
  83  		return result, fmt.Errorf("%w: tip is zero", ErrNoTip)
  84  	}
  85  
  86  	end := tip
  87  	var sinceMatch uint32
  88  
  89  	for {
  90  		if ctx.Err() != nil {
  91  			return result, ctx.Err()
  92  		}
  93  
  94  		start := uint32(0)
  95  
  96  		if end >= opts.Window {
  97  			start = end - opts.Window + 1
  98  		}
  99  
 100  		if start < opts.Floor {
 101  			start = opts.Floor
 102  		}
 103  
 104  		if err := chain.Fetch(ctx, start, end); err != nil {
 105  			return result, fmt.Errorf("scanner: fetch %d..%d: %w", start, end, err)
 106  		}
 107  
 108  		matched, err := chain.Match(ctx, start, end, scripts)
 109  
 110  		if err != nil {
 111  			return result, fmt.Errorf("scanner: match %d..%d: %w", start, end, err)
 112  		}
 113  
 114  		// Newest first, so a caller can act on the most likely coin before the walk finishes.
 115  		for i := len(matched) - 1; i >= 0; i-- {
 116  			height := matched[i]
 117  			result.Matched = append(result.Matched, height)
 118  
 119  			if opts.OnMatch != nil {
 120  				if err := opts.OnMatch(ctx, height); err != nil {
 121  					return result, err
 122  				}
 123  			}
 124  		}
 125  
 126  		scanned := end - start + 1
 127  		result.Scanned += scanned
 128  		result.Lowest = start
 129  
 130  		if len(matched) > 0 {
 131  			sinceMatch = 0
 132  		} else {
 133  			sinceMatch += scanned
 134  		}
 135  
 136  		switch {
 137  		case start == opts.Floor:
 138  			result.Stopped = "floor"
 139  
 140  			return result, nil
 141  		case opts.Gap > 0 && sinceMatch >= opts.Gap:
 142  			result.Stopped = "gap"
 143  
 144  			return result, nil
 145  		}
 146  
 147  		if start == 0 {
 148  			result.Stopped = "tip"
 149  
 150  			return result, nil
 151  		}
 152  
 153  		end = start - 1
 154  	}
 155  }
 156