filtercache_test.go raw
1 package filtercache
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "io"
8 "sync"
9 "testing"
10 "time"
11
12 "git.smesh.lol/nostrino/pkg/cfevents"
13 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
14 "git.smesh.lol/nostrino/pkg/nostr"
15 "git.smesh.lol/nostrino/pkg/relay"
16 )
17
18 // query is a REQ as the relay receives it.
19 type query struct {
20 Kinds []int
21 Chain []string
22 Heights []string
23 Limit int
24 }
25
26 // fakeRelay answers a REQ with a fixed set of stored events and an EOSE, which
27 // is all a relay does for a stored query.
28 type fakeRelay struct {
29 events []nostr.Event
30 // replyEmpty answers every REQ with EOSE and no events.
31 replyEmpty bool
32
33 mu sync.Mutex
34 requests []query
35 }
36
37 func (f *fakeRelay) dial(string) (relay.Transport, error) {
38 t := &fakeTransport{in: make(chan []byte, 256), out: make(chan []byte, 8), closed: make(chan struct{})}
39
40 go t.pump(f)
41
42 return t, nil
43 }
44
45 type fakeTransport struct {
46 in chan []byte
47 out chan []byte
48 closed chan struct{}
49 once sync.Once
50 }
51
52 func (t *fakeTransport) WriteText(msg []byte) error {
53 cp := append([]byte(nil), msg...)
54
55 select {
56 case t.out <- cp:
57 return nil
58 case <-t.closed:
59 return errors.New("filtercache: closed")
60 }
61 }
62
63 func (t *fakeTransport) ReadMessage() ([]byte, error) {
64 select {
65 case msg := <-t.in:
66 return msg, nil
67 case <-t.closed:
68 return nil, io.EOF
69 }
70 }
71
72 func (t *fakeTransport) Close() error {
73 t.once.Do(func() { close(t.closed) })
74
75 return nil
76 }
77
78 // pump answers each REQ the client writes.
79 func (t *fakeTransport) pump(f *fakeRelay) {
80 for {
81 select {
82 case <-t.closed:
83 return
84 case raw := <-t.out:
85 var frame []json.RawMessage
86
87 if err := json.Unmarshal(raw, &frame); err != nil || len(frame) < 2 {
88 continue
89 }
90
91 var verb, id string
92
93 _ = json.Unmarshal(frame[0], &verb)
94 _ = json.Unmarshal(frame[1], &id)
95
96 switch verb {
97 case "REQ":
98 f.mu.Lock()
99 f.requests = append(f.requests, parseQuery(raw))
100 f.mu.Unlock()
101
102 if !f.replyEmpty {
103 for i := range f.events {
104 t.send(append(append([]byte(`["EVENT","`+id+`",`), f.events[i].AppendJSON(nil)...), ']'))
105 }
106 }
107
108 t.send([]byte(`["EOSE","` + id + `"]`))
109 case "CLOSE":
110 // A relay keeps the connection open after a CLOSE; only the
111 // subscription ends.
112 }
113 }
114 }
115 }
116
117 func (t *fakeTransport) send(msg []byte) {
118 select {
119 case t.in <- msg:
120 case <-t.closed:
121 }
122 }
123
124 // parseQuery reads the filter out of the REQ frame as it arrived.
125 func parseQuery(raw []byte) query {
126 var frame []json.RawMessage
127
128 if err := json.Unmarshal(raw, &frame); err != nil || len(frame) < 3 {
129 return query{}
130 }
131
132 var fields map[string]json.RawMessage
133
134 if err := json.Unmarshal(frame[2], &fields); err != nil {
135 return query{}
136 }
137
138 out := query{}
139
140 if kinds, ok := fields["kinds"]; ok {
141 _ = json.Unmarshal(kinds, &out.Kinds)
142 }
143
144 if limit, ok := fields["limit"]; ok {
145 _ = json.Unmarshal(limit, &out.Limit)
146 }
147
148 if chain, ok := fields["#"+cfevents.ChainTag]; ok {
149 _ = json.Unmarshal(chain, &out.Chain)
150 }
151
152 if heights, ok := fields["#"+cfevents.HeightTag]; ok {
153 _ = json.Unmarshal(heights, &out.Heights)
154 }
155
156 return out
157 }
158
159 // storedBatch builds one event holding the filters of [from, from+n).
160 func storedBatch(t *testing.T, chainName string, from uint32, filters [][]byte) nostr.Event {
161 t.Helper()
162
163 batch := &cfevents.Batch{Chain: chainName, From: from, At: 1700000000}
164
165 for _, filter := range filters {
166 if err := batch.Add(chainhash.DoubleHashH(filter), filter); err != nil {
167 t.Fatalf("add: %v", err)
168 }
169 }
170
171 ev, err := batch.Encode()
172 if err != nil {
173 t.Fatalf("encode: %v", err)
174 }
175
176 // The relay client verifies what it reads, so a stored event is signed the
177 // way a producing relay would have signed it.
178 if err := ev.Sign([32]byte{1, 2, 3, 4}); err != nil {
179 t.Fatalf("sign: %v", err)
180 }
181
182 return ev
183 }
184
185 // TestFiltersReturnsTheStoredRuns: what a relay holds is decoded and returned in
186 // ascending order, which is the order the client consumes.
187 func TestFiltersReturnsTheStoredRuns(t *testing.T) {
188 first := storedBatch(t, "btc", 1, [][]byte{{1, 1, 1}, {2, 2, 2}})
189 second := storedBatch(t, "btc", 3, [][]byte{{3, 3, 3}})
190
191 relayFake := &fakeRelay{events: []nostr.Event{second, first}}
192
193 cache, err := New(Config{
194 Chain: "btc",
195 Relays: []string{"wss://relay"},
196 Dial: relayFake.dial,
197 })
198 if err != nil {
199 t.Fatal(err)
200 }
201 defer cache.Close()
202
203 runs, err := cache.Filters(context.Background(), 1, 3)
204 if err != nil {
205 t.Fatalf("filters: %v", err)
206 }
207
208 if len(runs) != 2 {
209 t.Fatalf("got %d runs, want 2", len(runs))
210 }
211
212 if runs[0].From != 1 || runs[1].From != 3 {
213 t.Fatalf("runs start at %d and %d, want 1 and 3", runs[0].From, runs[1].From)
214 }
215
216 if len(runs[0].Filters) != 2 || len(runs[1].Filters) != 1 {
217 t.Fatalf("run sizes are %d and %d", len(runs[0].Filters), len(runs[1].Filters))
218 }
219 }
220
221 // TestQueryAsksForTheWindow: the request that reaches the relay names the chain
222 // and every height in the window, because a relay matches tag values and not
223 // ranges.
224 func TestQueryAsksForTheWindow(t *testing.T) {
225 relayFake := &fakeRelay{replyEmpty: true}
226
227 cache, err := New(Config{Chain: "btc", Relays: []string{"wss://relay"}, Dial: relayFake.dial})
228 if err != nil {
229 t.Fatal(err)
230 }
231 defer cache.Close()
232
233 if _, err := cache.Filters(context.Background(), 100, 102); err != nil {
234 t.Fatalf("filters: %v", err)
235 }
236
237 relayFake.mu.Lock()
238 defer relayFake.mu.Unlock()
239
240 if len(relayFake.requests) != 1 {
241 t.Fatalf("the relay saw %d requests, want 1", len(relayFake.requests))
242 }
243
244 got := relayFake.requests[0]
245
246 if len(got.Kinds) != 1 || got.Kinds[0] != cfevents.Kind {
247 t.Fatalf("the request asks for kinds %v", got.Kinds)
248 }
249
250 if len(got.Heights) != 3 {
251 t.Fatalf("the request names %d heights, want 3", len(got.Heights))
252 }
253
254 if len(got.Chain) != 1 || got.Chain[0] != "btc" {
255 t.Fatalf("the request names chain %v", got.Chain)
256 }
257 }
258
259 // TestOtherChainsAreIgnored: the chain tag is in the request, but a relay that
260 // answered loosely must not be able to hand this chain another chain's filters.
261 // They would fail verification anyway; not decoding them is cheaper.
262 func TestOtherChainsAreIgnored(t *testing.T) {
263 mine := storedBatch(t, "btc", 1, [][]byte{{1, 1}})
264 other := storedBatch(t, "blake", 1, [][]byte{{9, 9}})
265
266 relayFake := &fakeRelay{events: []nostr.Event{mine, other}}
267
268 cache, err := New(Config{Chain: "btc", Relays: []string{"wss://relay"}, Dial: relayFake.dial})
269 if err != nil {
270 t.Fatal(err)
271 }
272 defer cache.Close()
273
274 runs, err := cache.Filters(context.Background(), 1, 1)
275 if err != nil {
276 t.Fatalf("filters: %v", err)
277 }
278
279 if len(runs) != 1 {
280 t.Fatalf("got %d runs, want 1", len(runs))
281 }
282
283 if len(runs[0].Filters[0]) != 2 {
284 t.Fatalf("got the other chain's filter: %v", runs[0].Filters[0])
285 }
286 }
287
288 // TestUndecodableEventsAreSkipped: one bad event costs that event, not the
289 // window. A relay with a corrupted batch should still serve the good ones.
290 func TestUndecodableEventsAreSkipped(t *testing.T) {
291 good := storedBatch(t, "btc", 2, [][]byte{{2, 2}})
292
293 bad := nostr.Event{
294 Kind: cfevents.Kind,
295 CreatedAt: 1700000000,
296 Tags: nostr.Tags{{cfevents.ChainTag, "btc"}, {cfevents.HeightTag, "2"}},
297 Content: "not base64",
298 }
299
300 if err := bad.Sign([32]byte{5, 6, 7, 8}); err != nil {
301 t.Fatalf("sign: %v", err)
302 }
303
304 relayFake := &fakeRelay{events: []nostr.Event{bad, good}}
305
306 cache, err := New(Config{Chain: "btc", Relays: []string{"wss://relay"}, Dial: relayFake.dial})
307 if err != nil {
308 t.Fatal(err)
309 }
310 defer cache.Close()
311
312 runs, err := cache.Filters(context.Background(), 2, 2)
313 if err != nil {
314 t.Fatalf("filters: %v", err)
315 }
316
317 if len(runs) != 1 || runs[0].From != 2 {
318 t.Fatalf("got %d runs (%v), want the good one at 2", len(runs), runs)
319 }
320 }
321
322 // TestEmptyRelayIsNotAnError: a relay that holds nothing is a miss, and a miss
323 // is how the client falls back to the peer.
324 func TestEmptyRelayIsNotAnError(t *testing.T) {
325 relayFake := &fakeRelay{replyEmpty: true}
326
327 cache, err := New(Config{Chain: "btc", Relays: []string{"wss://relay"}, Dial: relayFake.dial})
328 if err != nil {
329 t.Fatal(err)
330 }
331 defer cache.Close()
332
333 runs, err := cache.Filters(context.Background(), 1, 10)
334 if err != nil {
335 t.Fatalf("an empty relay returned an error: %v", err)
336 }
337
338 if len(runs) != 0 {
339 t.Fatalf("got %d runs from an empty relay", len(runs))
340 }
341 }
342
343 // TestEveryWindowIsAsked: a miss is normal and must not stop the asks. The
344 // misses come first when a wallet scans below the cache's coverage, and giving
345 // up would abandon the range the cache could serve.
346 func TestEveryWindowIsAsked(t *testing.T) {
347 relayFake := &fakeRelay{replyEmpty: true}
348
349 cache, err := New(Config{Chain: "btc", Relays: []string{"wss://relay"}, Dial: relayFake.dial})
350 if err != nil {
351 t.Fatal(err)
352 }
353 defer cache.Close()
354
355 const windows = 5
356
357 for window := uint32(0); window < windows; window++ {
358 from := 1 + window*100
359
360 if _, err := cache.Filters(context.Background(), from, from+99); err != nil {
361 t.Fatalf("window %d: %v", window, err)
362 }
363 }
364
365 relayFake.mu.Lock()
366 asked := len(relayFake.requests)
367 relayFake.mu.Unlock()
368
369 if asked != windows {
370 t.Fatalf("the relay was asked %d times for %d windows", asked, windows)
371 }
372 }
373
374 // TestSecondRelayIsTriedAfterTheFirstFails: the relay list is a list, not a
375 // single endpoint.
376 func TestSecondRelayIsTriedAfterTheFirstFails(t *testing.T) {
377 good := storedBatch(t, "btc", 1, [][]byte{{5, 5}})
378 second := &fakeRelay{events: []nostr.Event{good}}
379
380 cache, err := New(Config{
381 Chain: "btc",
382 Relays: []string{"wss://dead", "wss://live"},
383 Dial: func(url string) (relay.Transport, error) {
384 if url == "wss://dead" {
385 return nil, errors.New("connection refused")
386 }
387
388 return second.dial(url)
389 },
390 Wait: 2 * time.Second,
391 })
392 if err != nil {
393 t.Fatal(err)
394 }
395 defer cache.Close()
396
397 runs, err := cache.Filters(context.Background(), 1, 1)
398 if err != nil {
399 t.Fatalf("filters: %v", err)
400 }
401
402 if len(runs) != 1 {
403 t.Fatalf("got %d runs from the second relay, want 1", len(runs))
404 }
405 }
406