// Package filtersync brings an instance's BIP157 filter chain up to what a peer // has, using btcd's message types and nothing reimplemented. // // The chain commits to the filters twice over: each block header commits to the // filter header chain through the filter-header fold, and the filter header // commits to the filter through its hash. So a peer cannot hand over a filter // that is not the chain's: this verifies every filter against the filter hash it // is filed under and every filter hash against the fold, starting from the // instance's own last filter header. // // It exists because building filters locally needs the scriptPubKey of every // output a block spends, which the canonical set does not carry, so the build // holds the set plus a script map in memory. Syncing them needs neither. package filtersync import ( "context" "fmt" "time" btcdhash "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/wire/v2" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/filterstore" "git.smesh.lol/btcd-lite/internal/store" "git.smesh.lol/btcd-lite/internal/v2peer" ) // Message carries the constants the protocol fixes. const ( // HeadersPerRequest is the most filter hashes one getcfheaders answers. HeadersPerRequest = 2000 // FiltersPerRequest is the most filters one getcfilters answers. A node // treats a request spanning a thousand blocks as legal and one spanning // more as a protocol error. FiltersPerRequest = 1000 // RequestTimeout bounds one request and its answer. RequestTimeout = 2 * time.Minute ) // Result is what a sync did. type Result struct { // From is the first height written. From uint32 // To is one past the last height written. To uint32 // Filters is how many filter bodies were stored. Filters int } // Sync brings the filter header chain and the filters up to the header store's // tip, using one peer connection. // // The filter-header records are dense from height 0: the fold starts from a zero // previous header, which is what BIP157 defines and what a chain whose filters // this instance did not get from an anchor needs. func Sync(ctx context.Context, p *v2peer.Peer, headers *store.HeaderStore, filters *filterstore.Store, logf func(string, ...any)) (Result, error) { if logf == nil { logf = func(string, ...any) {} } tip, _, ok := headers.HeaderTip() if !ok { return Result{}, fmt.Errorf("filtersync: the header store has no tip") } start, err := nextFilterHeight(headers) if err != nil { return Result{}, err } if start > tip { logf("filtersync: filter headers are current at %d", tip) return Result{From: start, To: start}, nil } res := Result{From: start} if err := syncHeaders(ctx, p, headers, start, tip, logf); err != nil { return res, err } filtersFrom, err := nextFilterBody(headers, filters, start, tip) if err != nil { return res, err } if filtersFrom <= tip { if err := syncBodies(ctx, p, headers, filters, filtersFrom, tip, &res, logf); err != nil { return res, err } } res.To = tip + 1 return res, nil } // nextFilterHeight is the first height whose filter header this instance does // not hold. The records are dense from 0, so it is the record count. func nextFilterHeight(headers *store.HeaderStore) (uint32, error) { tip, _, ok := headers.FilterHeaderTip() if !ok { return 0, nil } return tip + 1, nil } // nextFilterBody is the first height whose filter bytes are not stored. A body // is found through that height's block hash, so the walk asks the header store. func nextFilterBody(headers *store.HeaderStore, filters *filterstore.Store, from, tip uint32) (uint32, error) { for h := from; h <= tip; h++ { hdr, ok := headers.Header(h) if !ok { return 0, fmt.Errorf("filtersync: no header at %d", h) } if _, err := filters.Get(hdr.BlockHash()); err != nil { return h, nil } } return tip + 1, nil } // syncHeaders walks the filter-header chain. Every answer carries the previous // filter header, which is the fold of everything below it, so a response that // does not continue the one before it is refused. func syncHeaders(ctx context.Context, p *v2peer.Peer, headers *store.HeaderStore, from, tip uint32, logf func(string, ...any)) error { prev := chainhash.Hash{} if from > 0 { h, ok := headers.FilterHeader(from - 1) if !ok { return fmt.Errorf("filtersync: no local filter header at %d", from-1) } prev = h } for next := from; next <= tip; { // The stop hash is a block hash, not a height and not zero: a node looks // it up and disconnects the peer when it does not name a block. stop := min(next+HeadersPerRequest-1, tip) stopHdr, ok := headers.Header(stop) if !ok { return fmt.Errorf("filtersync: no header at %d", stop) } if err := p.Write(&wire.MsgGetCFHeaders{ FilterType: wire.GCSFilterRegular, StartHeight: next, StopHash: btcdhash.Hash(stopHdr.BlockHash()), }); err != nil { return fmt.Errorf("filtersync: getcfheaders %d: %w", next, err) } msg, err := await(p, &wire.MsgCFHeaders{}, RequestTimeout) if err != nil { return fmt.Errorf("filtersync: getcfheaders %d: %w", next, err) } cfh, ok := msg.Message.(*wire.MsgCFHeaders) if !ok { return fmt.Errorf("filtersync: getcfheaders %d answered %q", next, msg.Command) } if len(cfh.FilterHashes) == 0 { // Nothing above this height: the peer's filter chain is shorter // than its header chain, which is worth saying rather than looping. if next <= tip { logf("filtersync: the peer's filter headers end at %d, the header tip is %d", next-1, tip) } return nil } if chainhash.Hash(cfh.PrevFilterHeader) != prev { return fmt.Errorf("filtersync: the peer continues from filter header %s, this instance has %s at %d", cfh.PrevFilterHeader, prev, next-1) } for i, fh := range cfh.FilterHashes { h := next + uint32(i) if h > tip { break } prev = fold(chainhash.Hash(*fh), prev) if err := headers.PutFilterHeaderRecord(h, chainhash.Hash(*fh), prev); err != nil { return fmt.Errorf("filtersync: filter header %d: %w", h, err) } } next += uint32(len(cfh.FilterHashes)) } logf("filtersync: filter headers to %d", tip) return nil } // syncBodies fetches the filters themselves in batches and checks each one // against the hash the filter-header chain committed to. func syncBodies(ctx context.Context, p *v2peer.Peer, headers *store.HeaderStore, filters *filterstore.Store, from, tip uint32, res *Result, logf func(string, ...any)) error { for next := from; next <= tip; { stop := min(next+FiltersPerRequest-1, tip) stopHdr, ok := headers.Header(stop) if !ok { return fmt.Errorf("filtersync: no header at %d", stop) } if err := p.Write(&wire.MsgGetCFilters{ FilterType: wire.GCSFilterRegular, StartHeight: next, StopHash: btcdhash.Hash(stopHdr.BlockHash()), }); err != nil { return fmt.Errorf("filtersync: getcfilters %d-%d: %w", next, stop, err) } for h := next; h <= stop; h++ { msg, err := await(p, &wire.MsgCFilter{}, RequestTimeout) if err != nil { return fmt.Errorf("filtersync: getcfilters %d-%d at %d: %w", next, stop, h, err) } cf, ok := msg.Message.(*wire.MsgCFilter) if !ok { return fmt.Errorf("filtersync: getcfilters answered %q", msg.Command) } hdr, ok := headers.Header(h) if !ok { return fmt.Errorf("filtersync: no header at %d", h) } if chainhash.Hash(cf.BlockHash) != hdr.BlockHash() { return fmt.Errorf("filtersync: filter %d is for %s, the header is %s", h, cf.BlockHash, hdr.BlockHash()) } want, ok := headers.FilterHash(h) if !ok { return fmt.Errorf("filtersync: no filter hash recorded at %d", h) } if got := chainhash.DoubleHashH(cf.Data); got != want { return fmt.Errorf("filtersync: filter %d hashes to %s, the chain commits to %s", h, got, want) } if err := filters.Put(hdr.BlockHash(), cf.Data); err != nil { return fmt.Errorf("filtersync: store filter %d: %w", h, err) } res.Filters++ } next = stop + 1 if next <= tip && next%(FiltersPerRequest*20) == 0 { logf("filtersync: filters to %d of %d", next-1, tip) } } logf("filtersync: filters to %d, %d stored", tip, res.Filters) return nil } // await reads messages until one of the wanted type arrives. A peer that closes // the connection ends the wait with the reason it closed. func await(p *v2peer.Peer, want wire.Message, timeout time.Duration) (v2peer.Msg, error) { timer := time.NewTimer(timeout) defer timer.Stop() for { select { case <-timer.C: return v2peer.Msg{}, fmt.Errorf("no %s within %s", want.Command(), timeout) case msg, ok := <-p.Messages(): if !ok { return v2peer.Msg{}, fmt.Errorf("the connection ended: %w", p.Err()) } if msg.Command == want.Command() { return msg, nil } } } } // fold is BIP157's chain rule: the double SHA-256 of the filter hash and the // previous filter header. func fold(filterHash, prev chainhash.Hash) chainhash.Hash { buf := make([]byte, 0, 64) buf = append(buf, filterHash[:]...) buf = append(buf, prev[:]...) return chainhash.DoubleHashH(buf) }