1 // Package filtersync brings an instance's BIP157 filter chain up to what a peer
2 // has, using btcd's message types and nothing reimplemented.
3 //
4 // The chain commits to the filters twice over: each block header commits to the
5 // filter header chain through the filter-header fold, and the filter header
6 // commits to the filter through its hash. So a peer cannot hand over a filter
7 // that is not the chain's: this verifies every filter against the filter hash it
8 // is filed under and every filter hash against the fold, starting from the
9 // instance's own last filter header.
10 //
11 // It exists because building filters locally needs the scriptPubKey of every
12 // output a block spends, which the canonical set does not carry, so the build
13 // holds the set plus a script map in memory. Syncing them needs neither.
14 package filtersync
15 16 import (
17 "context"
18 "fmt"
19 "time"
20 21 btcdhash "github.com/btcsuite/btcd/chainhash/v2"
22 "github.com/btcsuite/btcd/wire/v2"
23 24 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
25 26 "git.smesh.lol/btcd-lite/internal/filterstore"
27 "git.smesh.lol/btcd-lite/internal/store"
28 "git.smesh.lol/btcd-lite/internal/v2peer"
29 )
30 31 // Message carries the constants the protocol fixes.
32 const (
33 // HeadersPerRequest is the most filter hashes one getcfheaders answers.
34 HeadersPerRequest = 2000
35 // FiltersPerRequest is the most filters one getcfilters answers. A node
36 // treats a request spanning a thousand blocks as legal and one spanning
37 // more as a protocol error.
38 FiltersPerRequest = 1000
39 // RequestTimeout bounds one request and its answer.
40 RequestTimeout = 2 * time.Minute
41 )
42 43 // Result is what a sync did.
44 type Result struct {
45 // From is the first height written.
46 From uint32
47 // To is one past the last height written.
48 To uint32
49 // Filters is how many filter bodies were stored.
50 Filters int
51 }
52 53 // Sync brings the filter header chain and the filters up to the header store's
54 // tip, using one peer connection.
55 //
56 // The filter-header records are dense from height 0: the fold starts from a zero
57 // previous header, which is what BIP157 defines and what a chain whose filters
58 // this instance did not get from an anchor needs.
59 func Sync(ctx context.Context, p *v2peer.Peer, headers *store.HeaderStore, filters *filterstore.Store, logf func(string, ...any)) (Result, error) {
60 if logf == nil {
61 logf = func(string, ...any) {}
62 }
63 tip, _, ok := headers.HeaderTip()
64 if !ok {
65 return Result{}, fmt.Errorf("filtersync: the header store has no tip")
66 }
67 start, err := nextFilterHeight(headers)
68 if err != nil {
69 return Result{}, err
70 }
71 if start > tip {
72 logf("filtersync: filter headers are current at %d", tip)
73 return Result{From: start, To: start}, nil
74 }
75 res := Result{From: start}
76 if err := syncHeaders(ctx, p, headers, start, tip, logf); err != nil {
77 return res, err
78 }
79 filtersFrom, err := nextFilterBody(headers, filters, start, tip)
80 if err != nil {
81 return res, err
82 }
83 if filtersFrom <= tip {
84 if err := syncBodies(ctx, p, headers, filters, filtersFrom, tip, &res, logf); err != nil {
85 return res, err
86 }
87 }
88 res.To = tip + 1
89 return res, nil
90 }
91 92 // nextFilterHeight is the first height whose filter header this instance does
93 // not hold. The records are dense from 0, so it is the record count.
94 func nextFilterHeight(headers *store.HeaderStore) (uint32, error) {
95 tip, _, ok := headers.FilterHeaderTip()
96 if !ok {
97 return 0, nil
98 }
99 return tip + 1, nil
100 }
101 102 // nextFilterBody is the first height whose filter bytes are not stored. A body
103 // is found through that height's block hash, so the walk asks the header store.
104 func nextFilterBody(headers *store.HeaderStore, filters *filterstore.Store, from, tip uint32) (uint32, error) {
105 for h := from; h <= tip; h++ {
106 hdr, ok := headers.Header(h)
107 if !ok {
108 return 0, fmt.Errorf("filtersync: no header at %d", h)
109 }
110 if _, err := filters.Get(hdr.BlockHash()); err != nil {
111 return h, nil
112 }
113 }
114 return tip + 1, nil
115 }
116 117 // syncHeaders walks the filter-header chain. Every answer carries the previous
118 // filter header, which is the fold of everything below it, so a response that
119 // does not continue the one before it is refused.
120 func syncHeaders(ctx context.Context, p *v2peer.Peer, headers *store.HeaderStore, from, tip uint32, logf func(string, ...any)) error {
121 prev := chainhash.Hash{}
122 if from > 0 {
123 h, ok := headers.FilterHeader(from - 1)
124 if !ok {
125 return fmt.Errorf("filtersync: no local filter header at %d", from-1)
126 }
127 prev = h
128 }
129 for next := from; next <= tip; {
130 // The stop hash is a block hash, not a height and not zero: a node looks
131 // it up and disconnects the peer when it does not name a block.
132 stop := min(next+HeadersPerRequest-1, tip)
133 stopHdr, ok := headers.Header(stop)
134 if !ok {
135 return fmt.Errorf("filtersync: no header at %d", stop)
136 }
137 if err := p.Write(&wire.MsgGetCFHeaders{
138 FilterType: wire.GCSFilterRegular, StartHeight: next,
139 StopHash: btcdhash.Hash(stopHdr.BlockHash()),
140 }); err != nil {
141 return fmt.Errorf("filtersync: getcfheaders %d: %w", next, err)
142 }
143 msg, err := await(p, &wire.MsgCFHeaders{}, RequestTimeout)
144 if err != nil {
145 return fmt.Errorf("filtersync: getcfheaders %d: %w", next, err)
146 }
147 cfh, ok := msg.Message.(*wire.MsgCFHeaders)
148 if !ok {
149 return fmt.Errorf("filtersync: getcfheaders %d answered %q", next, msg.Command)
150 }
151 if len(cfh.FilterHashes) == 0 {
152 // Nothing above this height: the peer's filter chain is shorter
153 // than its header chain, which is worth saying rather than looping.
154 if next <= tip {
155 logf("filtersync: the peer's filter headers end at %d, the header tip is %d", next-1, tip)
156 }
157 return nil
158 }
159 if chainhash.Hash(cfh.PrevFilterHeader) != prev {
160 return fmt.Errorf("filtersync: the peer continues from filter header %s, this instance has %s at %d",
161 cfh.PrevFilterHeader, prev, next-1)
162 }
163 for i, fh := range cfh.FilterHashes {
164 h := next + uint32(i)
165 if h > tip {
166 break
167 }
168 prev = fold(chainhash.Hash(*fh), prev)
169 if err := headers.PutFilterHeaderRecord(h, chainhash.Hash(*fh), prev); err != nil {
170 return fmt.Errorf("filtersync: filter header %d: %w", h, err)
171 }
172 }
173 next += uint32(len(cfh.FilterHashes))
174 }
175 logf("filtersync: filter headers to %d", tip)
176 return nil
177 }
178 179 // syncBodies fetches the filters themselves in batches and checks each one
180 // against the hash the filter-header chain committed to.
181 func syncBodies(ctx context.Context, p *v2peer.Peer, headers *store.HeaderStore, filters *filterstore.Store, from, tip uint32, res *Result, logf func(string, ...any)) error {
182 for next := from; next <= tip; {
183 stop := min(next+FiltersPerRequest-1, tip)
184 stopHdr, ok := headers.Header(stop)
185 if !ok {
186 return fmt.Errorf("filtersync: no header at %d", stop)
187 }
188 if err := p.Write(&wire.MsgGetCFilters{
189 FilterType: wire.GCSFilterRegular, StartHeight: next,
190 StopHash: btcdhash.Hash(stopHdr.BlockHash()),
191 }); err != nil {
192 return fmt.Errorf("filtersync: getcfilters %d-%d: %w", next, stop, err)
193 }
194 for h := next; h <= stop; h++ {
195 msg, err := await(p, &wire.MsgCFilter{}, RequestTimeout)
196 if err != nil {
197 return fmt.Errorf("filtersync: getcfilters %d-%d at %d: %w", next, stop, h, err)
198 }
199 cf, ok := msg.Message.(*wire.MsgCFilter)
200 if !ok {
201 return fmt.Errorf("filtersync: getcfilters answered %q", msg.Command)
202 }
203 hdr, ok := headers.Header(h)
204 if !ok {
205 return fmt.Errorf("filtersync: no header at %d", h)
206 }
207 if chainhash.Hash(cf.BlockHash) != hdr.BlockHash() {
208 return fmt.Errorf("filtersync: filter %d is for %s, the header is %s", h, cf.BlockHash, hdr.BlockHash())
209 }
210 want, ok := headers.FilterHash(h)
211 if !ok {
212 return fmt.Errorf("filtersync: no filter hash recorded at %d", h)
213 }
214 if got := chainhash.DoubleHashH(cf.Data); got != want {
215 return fmt.Errorf("filtersync: filter %d hashes to %s, the chain commits to %s", h, got, want)
216 }
217 if err := filters.Put(hdr.BlockHash(), cf.Data); err != nil {
218 return fmt.Errorf("filtersync: store filter %d: %w", h, err)
219 }
220 res.Filters++
221 }
222 next = stop + 1
223 if next <= tip && next%(FiltersPerRequest*20) == 0 {
224 logf("filtersync: filters to %d of %d", next-1, tip)
225 }
226 }
227 logf("filtersync: filters to %d, %d stored", tip, res.Filters)
228 return nil
229 }
230 231 // await reads messages until one of the wanted type arrives. A peer that closes
232 // the connection ends the wait with the reason it closed.
233 func await(p *v2peer.Peer, want wire.Message, timeout time.Duration) (v2peer.Msg, error) {
234 timer := time.NewTimer(timeout)
235 defer timer.Stop()
236 for {
237 select {
238 case <-timer.C:
239 return v2peer.Msg{}, fmt.Errorf("no %s within %s", want.Command(), timeout)
240 case msg, ok := <-p.Messages():
241 if !ok {
242 return v2peer.Msg{}, fmt.Errorf("the connection ended: %w", p.Err())
243 }
244 if msg.Command == want.Command() {
245 return msg, nil
246 }
247 }
248 }
249 }
250 251 // fold is BIP157's chain rule: the double SHA-256 of the filter hash and the
252 // previous filter header.
253 func fold(filterHash, prev chainhash.Hash) chainhash.Hash {
254 buf := make([]byte, 0, 64)
255 buf = append(buf, filterHash[:]...)
256 buf = append(buf, prev[:]...)
257 return chainhash.DoubleHashH(buf)
258 }
259