window.go raw

   1  // Package relay carries client transactions onto the network and keeps the
   2  // window of what it relayed and what the served chain has since said about
   3  // them.
   4  //
   5  // It is not a mempool. It builds no templates, replaces no policy and does not
   6  // claim a transaction was accepted: the peer protocol says nothing back for a
   7  // transaction it keeps or drops, so the honest states are the ones the
   8  // instance can see for itself. `announced` is that the bytes went to a peer;
   9  // `seen` is that a verified block's filter matches one of the scripts the
  10  // transaction funds; `spent` is that plus the canonical UTXO set recording the
  11  // transaction's inputs as spent at that height. The first is a fact about this
  12  // instance, the second is evidence, and the third is exact where the instance
  13  // holds the store.
  14  package relay
  15  
  16  import (
  17  	"sync"
  18  	"time"
  19  
  20  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  21  	gcs "git.smesh.lol/nostrino/pkg/filter"
  22  
  23  	"git.smesh.lol/btcd-lite/internal/wire"
  24  )
  25  
  26  // State is what the window knows about a relayed transaction.
  27  type State uint8
  28  
  29  const (
  30  	// Announced means the bytes were written to a peer. It is not acceptance.
  31  	Announced State = iota + 1
  32  	// Seen means a verified block's filter matched a funded script.
  33  	Seen
  34  	// Spent means a verified block's filter matched a funded script and the
  35  	// UTXO set records the inputs as spent at that height.
  36  	Spent
  37  )
  38  
  39  // String names a state as the API returns it.
  40  func (s State) String() string {
  41  	switch s {
  42  	case Announced:
  43  		return "announced"
  44  	case Seen:
  45  		return "seen"
  46  	case Spent:
  47  		return "spent"
  48  	}
  49  	return "unknown"
  50  }
  51  
  52  // Entry is one relayed transaction and what is known of it.
  53  type Entry struct {
  54  	TxID chainhash.Hash
  55  	Raw  []byte
  56  	// Scripts are the scriptPubKeys the transaction funds; a filter hit on
  57  	// any of them is what takes the entry to Seen.
  58  	Scripts [][]byte
  59  	// Inputs are the outpoints it spends, for the store's answer on whether
  60  	// the spend happened at the height that matched.
  61  	Inputs    []wire.OutPoint
  62  	State     State
  63  	Height    uint32 // the height of the block that took it to Seen or Spent
  64  	Announced time.Time
  65  	// Size is the serialized size, for the window's byte budget.
  66  	Size int
  67  }
  68  
  69  // Window is the bounded set of relayed transactions.
  70  type Window struct {
  71  	mu      sync.RWMutex
  72  	entries map[chainhash.Hash]*Entry
  73  	// order is the arrival order, oldest first, which is the order eviction
  74  	// takes them in.
  75  	order  []chainhash.Hash
  76  	bytes  int
  77  	budget int
  78  	clock  func() time.Time
  79  }
  80  
  81  // NewWindow returns a window bounded by bytes. Zero means 128 MiB.
  82  func NewWindow(budget int) *Window {
  83  	if budget <= 0 {
  84  		budget = 128 << 20
  85  	}
  86  	return &Window{entries: map[chainhash.Hash]*Entry{}, budget: budget, clock: time.Now}
  87  }
  88  
  89  // Add files a relayed transaction. A transaction already in the window is
  90  // returned as it stands, with already true: a relay is idempotent.
  91  func (w *Window) Add(e *Entry) (*Entry, bool) {
  92  	w.mu.Lock()
  93  	defer w.mu.Unlock()
  94  	if old, ok := w.entries[e.TxID]; ok {
  95  		return cloneEntry(old), true
  96  	}
  97  	e.Announced = w.clock()
  98  	e.State = Announced
  99  	w.entries[e.TxID] = e
 100  	w.order = append(w.order, e.TxID)
 101  	w.bytes += e.Size
 102  	for w.bytes > w.budget && len(w.order) > 0 {
 103  		oldest := w.order[0]
 104  		w.order = w.order[1:]
 105  		if gone, ok := w.entries[oldest]; ok {
 106  			w.bytes -= gone.Size
 107  			delete(w.entries, oldest)
 108  		}
 109  	}
 110  	return cloneEntry(e), false
 111  }
 112  
 113  // Get returns one entry.
 114  func (w *Window) Get(id chainhash.Hash) (*Entry, bool) {
 115  	w.mu.RLock()
 116  	defer w.mu.RUnlock()
 117  	e, ok := w.entries[id]
 118  	if !ok {
 119  		return nil, false
 120  	}
 121  	return cloneEntry(e), true
 122  }
 123  
 124  // Len is the number of entries, and Bytes the budget in use.
 125  func (w *Window) Len() int {
 126  	w.mu.RLock()
 127  	defer w.mu.RUnlock()
 128  	return len(w.entries)
 129  }
 130  
 131  // Bytes is the serialized size of everything held.
 132  func (w *Window) Bytes() int {
 133  	w.mu.RLock()
 134  	defer w.mu.RUnlock()
 135  	return w.bytes
 136  }
 137  
 138  // Due returns the entries whose announcement is old enough to repeat.
 139  func (w *Window) Due(age time.Duration) []*Entry {
 140  	w.mu.Lock()
 141  	defer w.mu.Unlock()
 142  	now := w.clock()
 143  	var out []*Entry
 144  	for _, id := range w.order {
 145  		e := w.entries[id]
 146  		if e == nil || e.State != Announced {
 147  			continue
 148  		}
 149  		if now.Sub(e.Announced) >= age {
 150  			out = append(out, cloneEntry(e))
 151  		}
 152  	}
 153  	return out
 154  }
 155  
 156  // Announced marks an entry as announced again, which restarts its age.
 157  func (w *Window) Announced(id chainhash.Hash) {
 158  	w.mu.Lock()
 159  	defer w.mu.Unlock()
 160  	if e, ok := w.entries[id]; ok {
 161  		e.Announced = w.clock()
 162  	}
 163  }
 164  
 165  // Settle takes every entry to the state a block gives it: an entry whose
 166  // funded scripts match the block's filter is seen, and one whose inputs the
 167  // store reports spent at that height is spent.
 168  //
 169  // filter is the block's verified BIP158 filter and height its height; lookup
 170  // answers "is this outpoint spent, and at what height" from the canonical set,
 171  // and may be nil on an instance that holds no UTXO data, in which case the
 172  // entries stop at Seen.
 173  func (w *Window) Settle(height uint32, blockHash chainhash.Hash, filter []byte, lookup SpentAt) []*Entry {
 174  	w.mu.Lock()
 175  	defer w.mu.Unlock()
 176  	var changed []*Entry
 177  	for _, id := range w.order {
 178  		e := w.entries[id]
 179  		if e == nil || e.State == Spent {
 180  			continue
 181  		}
 182  		hit, err := filterMatches(filter, blockHash, e.Scripts)
 183  		if err != nil || !hit {
 184  			continue
 185  		}
 186  		if lookup == nil {
 187  			if e.State < Seen {
 188  				e.State, e.Height = Seen, height
 189  				changed = append(changed, cloneEntry(e))
 190  			}
 191  			continue
 192  		}
 193  		allSpent := len(e.Inputs) > 0
 194  		for _, op := range e.Inputs {
 195  			if at, ok := lookup(op); !ok || at != height {
 196  				allSpent = false
 197  				break
 198  			}
 199  		}
 200  		if allSpent {
 201  			e.State, e.Height = Spent, height
 202  		} else if e.State < Seen {
 203  			e.State, e.Height = Seen, height
 204  		} else {
 205  			continue
 206  		}
 207  		changed = append(changed, cloneEntry(e))
 208  	}
 209  	return changed
 210  }
 211  
 212  // SpentAt answers whether an outpoint is spent and at which height.
 213  type SpentAt func(op wire.OutPoint) (uint32, bool)
 214  
 215  // filterMatches is the BIP158 match against an imported filter and keyed by
 216  // the block hash in internal byte order, the order the filter was built with.
 217  func filterMatches(filter []byte, blockHash chainhash.Hash, scripts [][]byte) (bool, error) {
 218  	return gcs.Match(filter, blockHash, scripts)
 219  }
 220  
 221  // LookupFromSet answers SpentAt from a canonical set and a spending height per
 222  // outpoint.
 223  func LookupFromSet(spent map[wire.OutPoint]uint32) SpentAt {
 224  	return func(op wire.OutPoint) (uint32, bool) {
 225  		at, ok := spent[op]
 226  		return at, ok
 227  	}
 228  }
 229  
 230  // InputsOf returns the outpoints a parsed transaction spends.
 231  func InputsOf(tx *wire.Tx) []wire.OutPoint {
 232  	out := make([]wire.OutPoint, 0, len(tx.TxIn))
 233  	for i := range tx.TxIn {
 234  		out = append(out, tx.TxIn[i].PreviousOutPoint)
 235  	}
 236  	return out
 237  }
 238  
 239  // ScriptsOf returns the scriptPubKeys a parsed transaction funds.
 240  func ScriptsOf(tx *wire.Tx) [][]byte {
 241  	out := make([][]byte, 0, len(tx.TxOut))
 242  	for i := range tx.TxOut {
 243  		out = append(out, tx.TxOut[i].PkScript)
 244  	}
 245  	return out
 246  }
 247  
 248  func cloneEntry(e *Entry) *Entry {
 249  	c := *e
 250  	c.Scripts = append([][]byte(nil), e.Scripts...)
 251  	c.Inputs = append([]wire.OutPoint(nil), e.Inputs...)
 252  	return &c
 253  }
 254