package relay import ( "context" "time" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/store" ) // Follow settles the window as the chain advances: every new block's verified // filter is matched against the window, and a block that matches takes the // entries it touches to Seen or Spent. // // It reads the filter chain the instance already holds and verifies it the way // every other reader does: the filter's hash against the filter hash the // header chain commits to. A filter that does not verify ends the pass rather // than being used. func (r *Relay) Follow(ctx context.Context, headers *store.HeaderStore, lookup SpentAt, every time.Duration) { if every <= 0 { every = 15 * time.Second } t := time.NewTicker(every) defer t.Stop() // The pass starts at the base filter's height: an entry filed after the // base was built is still found by the block whose filter already // existed, because the window is settled against every block the instance // holds and the states keep their first evidence. next := uint32(0) if a, ok := headers.Anchor(); ok && a.FilterHeight >= 0 { next = uint32(a.FilterHeight) + 1 } for ctx.Err() == nil { select { case <-ctx.Done(): return case <-t.C: } tip, ok := headers.FilterTip() if !ok { continue } // The walk starts above the anchor, because the anchor's own filter // header and filter are the trusted starting point and not records; a // height with no filter in the store is where the store's coverage // ends, and an entry filed above it settles when the blocks arrive. for h := next; h <= tip; h++ { flt, ok := headers.Filter(h) if !ok { break } want, ok := headers.FilterHash(h) if !ok || chainhash.DoubleHashH(flt) != want { r.cfg.Logf("relay: filter at %d does not verify; not settling with it", h) next = h break } header, ok := headers.Header(h) if !ok { next = h break } // The block hash the filter was keyed with is the header's, in // internal order: Header returns the record neutrino holds. blockHash := header.BlockHash() for _, e := range r.window.Settle(h, blockHash, flt, lookup) { r.cfg.Logf("relay: %s is %s at %d", e.TxID, e.State, h) } next = h + 1 } } } // Rebroadcast re-announces the window's unconfirmed transactions every age, // jittered per instance so two instances do not announce in lockstep. func (r *Relay) Rebroadcast(ctx context.Context, age time.Duration) { if age <= 0 { age = 45 * time.Minute } t := time.NewTicker(age / 3) defer t.Stop() for ctx.Err() == nil { select { case <-ctx.Done(): return case <-t.C: } due := r.window.Due(age) if len(due) == 0 { continue } ids := make([]chainhash.Hash, len(due)) for i, e := range due { ids[i] = e.TxID } if n, err := r.Announce(ctx, ids); err != nil { r.cfg.Logf("relay: rebroadcast: %v", err) } else if n > 0 { for _, e := range due { r.window.Announced(e.TxID) } r.cfg.Logf("relay: re-announced %d transactions to %d peers", len(ids), n) } } }