// Package relay carries client transactions onto the network and keeps the // window of what it relayed and what the served chain has since said about // them. // // It is not a mempool. It builds no templates, replaces no policy and does not // claim a transaction was accepted: the peer protocol says nothing back for a // transaction it keeps or drops, so the honest states are the ones the // instance can see for itself. `announced` is that the bytes went to a peer; // `seen` is that a verified block's filter matches one of the scripts the // transaction funds; `spent` is that plus the canonical UTXO set recording the // transaction's inputs as spent at that height. The first is a fact about this // instance, the second is evidence, and the third is exact where the instance // holds the store. package relay import ( "sync" "time" "git.smesh.lol/nostrino/pkg/crypto/chainhash" gcs "git.smesh.lol/nostrino/pkg/filter" "git.smesh.lol/btcd-lite/internal/wire" ) // State is what the window knows about a relayed transaction. type State uint8 const ( // Announced means the bytes were written to a peer. It is not acceptance. Announced State = iota + 1 // Seen means a verified block's filter matched a funded script. Seen // Spent means a verified block's filter matched a funded script and the // UTXO set records the inputs as spent at that height. Spent ) // String names a state as the API returns it. func (s State) String() string { switch s { case Announced: return "announced" case Seen: return "seen" case Spent: return "spent" } return "unknown" } // Entry is one relayed transaction and what is known of it. type Entry struct { TxID chainhash.Hash Raw []byte // Scripts are the scriptPubKeys the transaction funds; a filter hit on // any of them is what takes the entry to Seen. Scripts [][]byte // Inputs are the outpoints it spends, for the store's answer on whether // the spend happened at the height that matched. Inputs []wire.OutPoint State State Height uint32 // the height of the block that took it to Seen or Spent Announced time.Time // Size is the serialized size, for the window's byte budget. Size int } // Window is the bounded set of relayed transactions. type Window struct { mu sync.RWMutex entries map[chainhash.Hash]*Entry // order is the arrival order, oldest first, which is the order eviction // takes them in. order []chainhash.Hash bytes int budget int clock func() time.Time } // NewWindow returns a window bounded by bytes. Zero means 128 MiB. func NewWindow(budget int) *Window { if budget <= 0 { budget = 128 << 20 } return &Window{entries: map[chainhash.Hash]*Entry{}, budget: budget, clock: time.Now} } // Add files a relayed transaction. A transaction already in the window is // returned as it stands, with already true: a relay is idempotent. func (w *Window) Add(e *Entry) (*Entry, bool) { w.mu.Lock() defer w.mu.Unlock() if old, ok := w.entries[e.TxID]; ok { return cloneEntry(old), true } e.Announced = w.clock() e.State = Announced w.entries[e.TxID] = e w.order = append(w.order, e.TxID) w.bytes += e.Size for w.bytes > w.budget && len(w.order) > 0 { oldest := w.order[0] w.order = w.order[1:] if gone, ok := w.entries[oldest]; ok { w.bytes -= gone.Size delete(w.entries, oldest) } } return cloneEntry(e), false } // Get returns one entry. func (w *Window) Get(id chainhash.Hash) (*Entry, bool) { w.mu.RLock() defer w.mu.RUnlock() e, ok := w.entries[id] if !ok { return nil, false } return cloneEntry(e), true } // Len is the number of entries, and Bytes the budget in use. func (w *Window) Len() int { w.mu.RLock() defer w.mu.RUnlock() return len(w.entries) } // Bytes is the serialized size of everything held. func (w *Window) Bytes() int { w.mu.RLock() defer w.mu.RUnlock() return w.bytes } // Due returns the entries whose announcement is old enough to repeat. func (w *Window) Due(age time.Duration) []*Entry { w.mu.Lock() defer w.mu.Unlock() now := w.clock() var out []*Entry for _, id := range w.order { e := w.entries[id] if e == nil || e.State != Announced { continue } if now.Sub(e.Announced) >= age { out = append(out, cloneEntry(e)) } } return out } // Announced marks an entry as announced again, which restarts its age. func (w *Window) Announced(id chainhash.Hash) { w.mu.Lock() defer w.mu.Unlock() if e, ok := w.entries[id]; ok { e.Announced = w.clock() } } // Settle takes every entry to the state a block gives it: an entry whose // funded scripts match the block's filter is seen, and one whose inputs the // store reports spent at that height is spent. // // filter is the block's verified BIP158 filter and height its height; lookup // answers "is this outpoint spent, and at what height" from the canonical set, // and may be nil on an instance that holds no UTXO data, in which case the // entries stop at Seen. func (w *Window) Settle(height uint32, blockHash chainhash.Hash, filter []byte, lookup SpentAt) []*Entry { w.mu.Lock() defer w.mu.Unlock() var changed []*Entry for _, id := range w.order { e := w.entries[id] if e == nil || e.State == Spent { continue } hit, err := filterMatches(filter, blockHash, e.Scripts) if err != nil || !hit { continue } if lookup == nil { if e.State < Seen { e.State, e.Height = Seen, height changed = append(changed, cloneEntry(e)) } continue } allSpent := len(e.Inputs) > 0 for _, op := range e.Inputs { if at, ok := lookup(op); !ok || at != height { allSpent = false break } } if allSpent { e.State, e.Height = Spent, height } else if e.State < Seen { e.State, e.Height = Seen, height } else { continue } changed = append(changed, cloneEntry(e)) } return changed } // SpentAt answers whether an outpoint is spent and at which height. type SpentAt func(op wire.OutPoint) (uint32, bool) // filterMatches is the BIP158 match against an imported filter and keyed by // the block hash in internal byte order, the order the filter was built with. func filterMatches(filter []byte, blockHash chainhash.Hash, scripts [][]byte) (bool, error) { return gcs.Match(filter, blockHash, scripts) } // LookupFromSet answers SpentAt from a canonical set and a spending height per // outpoint. func LookupFromSet(spent map[wire.OutPoint]uint32) SpentAt { return func(op wire.OutPoint) (uint32, bool) { at, ok := spent[op] return at, ok } } // InputsOf returns the outpoints a parsed transaction spends. func InputsOf(tx *wire.Tx) []wire.OutPoint { out := make([]wire.OutPoint, 0, len(tx.TxIn)) for i := range tx.TxIn { out = append(out, tx.TxIn[i].PreviousOutPoint) } return out } // ScriptsOf returns the scriptPubKeys a parsed transaction funds. func ScriptsOf(tx *wire.Tx) [][]byte { out := make([][]byte, 0, len(tx.TxOut)) for i := range tx.TxOut { out = append(out, tx.TxOut[i].PkScript) } return out } func cloneEntry(e *Entry) *Entry { c := *e c.Scripts = append([][]byte(nil), e.Scripts...) c.Inputs = append([]wire.OutPoint(nil), e.Inputs...) return &c }