package cfevents import ( "encoding/base64" "errors" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/nostr" ) // batch builds a batch of n filters at From, with hashes that match the filter // bytes, which is what a correct producer publishes. func batch(from uint32, sizes ...int) *Batch { b := &Batch{Chain: "btc", From: from, At: 1750000000} for i, n := range sizes { filter := make([]byte, n) for j := range filter { filter[j] = byte(i*7 + j*13) } if err := b.Add(chainhash.DoubleHashH(filter), filter); err != nil { panic(err) } } return b } // committedFor returns the committed-hash lookup a client with a matching store // would provide. func committedFor(b *Batch) func(uint32) (chainhash.Hash, bool) { return func(h uint32) (chainhash.Hash, bool) { i := int(h) - int(b.From) if i < 0 || i >= len(b.Hashes) { return chainhash.Hash{}, false } return b.Hashes[i], true } } // TestRoundTrip: what the producer encodes is what the consumer decodes, tags // and bytes included. The event id is stable for the same batch, which is what // makes a republished batch cost a duplicate answer instead of a second event. func TestRoundTrip(t *testing.T) { orig := batch(961631, 900, 1200, 40) ev, err := orig.Encode() if err != nil { t.Fatalf("encode: %v", err) } ev.Sign([32]byte{1, 2, 3}) firstID := ev.ID got, err := Decode(&ev) if err != nil { t.Fatalf("decode: %v", err) } if got.Chain != orig.Chain || got.From != orig.From || got.To() != orig.To() || got.At != orig.At { t.Fatalf("header differs: got %+v, want chain=%s from=%d to=%d at=%d", got, orig.Chain, orig.From, orig.To(), orig.At) } if len(got.Filters) != len(orig.Filters) { t.Fatalf("got %d filters, want %d", len(got.Filters), len(orig.Filters)) } for i := range orig.Filters { if string(got.Filters[i]) != string(orig.Filters[i]) { t.Fatalf("filter %d differs", i) } if got.Hashes[i] != orig.Hashes[i] { t.Fatalf("hash %d differs", i) } } // Re-encoding the same batch must produce the same id, or a restarted // producer would grow the relay's store instead of hitting a duplicate. again, err := got.Encode() if err != nil { t.Fatalf("re-encode: %v", err) } again.Sign([32]byte{1, 2, 3}) if again.ID != firstID { t.Fatal("the same batch encoded to a different event id") } } // TestTakeRejectsWrongFilter: a batch whose bytes do not hash to the hash it // carries must not be stored. The height is left out of the result so the // consumer fetches it from a peer. func TestTakeRejectsWrongFilter(t *testing.T) { orig := batch(100, 500, 600) ev, err := orig.Encode() if err != nil { t.Fatalf("encode: %v", err) } // Corrupt one filter without touching its hash, the way a producer bug or a // tampering relay would. body, err := base64.StdEncoding.DecodeString(ev.Content) if err != nil { t.Fatalf("decode body: %v", err) } body[len(body)-1] ^= 0xff ev.Content = base64.StdEncoding.EncodeToString(body) got, err := Decode(&ev) if err != nil { t.Fatalf("decode: %v", err) } taken, err := got.Take(committedFor(orig)) if err != nil { t.Fatalf("take: %v", err) } if len(taken) != 1 { t.Fatalf("took %d filters, want 1", len(taken)) } if _, ok := taken[100]; !ok { t.Fatalf("the untouched filter was dropped: %v", taken) } if _, ok := taken[101]; ok { t.Fatal("the corrupted filter was stored") } } // TestTakeRejectsWrongChain: when the first filter hash is not the committed // one the batch is for another chain or a fork, and none of it may be stored. func TestTakeRejectsWrongChain(t *testing.T) { orig := batch(100, 500, 600) ev, err := orig.Encode() if err != nil { t.Fatalf("encode: %v", err) } got, err := Decode(&ev) if err != nil { t.Fatalf("decode: %v", err) } other := func(uint32) (chainhash.Hash, bool) { return chainhash.HashH([]byte("other")), true } if _, err := got.Take(other); err == nil { t.Fatal("a batch from another chain was accepted") } } // TestTakeWithoutCommitment: a consumer with no filter hash at that height // cannot judge the batch, so it gets nothing and no error. That is the range it // has not synced yet, and the peer answers it as it always did. func TestTakeWithoutCommitment(t *testing.T) { got := batch(100, 500) taken, err := got.Take(func(uint32) (chainhash.Hash, bool) { return chainhash.Hash{}, false }) if err != nil { t.Fatalf("take: %v", err) } if len(taken) != 0 { t.Fatalf("took %d filters with no commitment", len(taken)) } } // TestDecodeRejectsTruncatedBody: a body that ends inside a filter must be an // error, not a short batch. Reading past what arrived is how a decoder turns // into a random number generator. func TestDecodeRejectsTruncatedBody(t *testing.T) { orig := batch(100, 500, 600) ev, err := orig.Encode() if err != nil { t.Fatalf("encode: %v", err) } body, err := base64.StdEncoding.DecodeString(ev.Content) if err != nil { t.Fatalf("decode body: %v", err) } for _, cut := range []int{0, 2, 4, 10, len(body) / 2, len(body) - 1} { ev.Content = base64.StdEncoding.EncodeToString(body[:cut]) if _, err := Decode(&ev); err == nil { t.Fatalf("decoded a body truncated to %d of %d bytes", cut, len(body)) } } } // TestDecodeRejectsTagMismatch: the tags say how many filters the body holds. // A batch whose tags and body disagree is malformed, and a consumer that // trusted either one alone would store filters at the wrong heights. func TestDecodeRejectsTagMismatch(t *testing.T) { orig := batch(100, 500, 600) ev, err := orig.Encode() if err != nil { t.Fatalf("encode: %v", err) } for i, tag := range ev.Tags { if tag.Name() == "to" { ev.Tags[i] = nostr.Tag{"to", "102"} } } if _, err := Decode(&ev); err == nil { t.Fatal("decoded a batch whose tag range exceeds its body") } } // TestQueryNamesEveryHeight: the query is what a consumer sends to find a // batch, and a relay matches tag values exactly. A query that named only the // ends of the range would return nothing, because no event carries a tag for // "anything between 900 and 950". func TestQueryNamesEveryHeight(t *testing.T) { q := Query("btc", 900, 950) if len(q.Tags[HeightTag]) != 51 { t.Fatalf("query names %d heights, want 51", len(q.Tags[HeightTag])) } if q.Tags[HeightTag][0] != "900" || q.Tags[HeightTag][50] != "950" { t.Fatalf("query heights run %s..%s", q.Tags[HeightTag][0], q.Tags[HeightTag][50]) } if len(q.Tags[ChainTag]) != 1 || q.Tags[ChainTag][0] != "btc" { t.Fatalf("query chain is %v", q.Tags[ChainTag]) } if q.Limit != 51 { t.Fatalf("query limit is %d, want 51", q.Limit) } // The query has to match the events the producer writes, or the cache is // unreachable no matter how correct the filters are. b := batch(900, 100, 100) ev, err := b.Encode() if err != nil { t.Fatalf("encode: %v", err) } if !q.Matches(&ev) { t.Fatal("the query does not match a batch it was built for") } other := batch(950, 100) otherEv, err := other.Encode() if err != nil { t.Fatalf("encode: %v", err) } if !q.Matches(&otherEv) { t.Fatal("the query does not match a batch that covers its last height") } far := batch(1000, 100) farEv, err := far.Encode() if err != nil { t.Fatalf("encode: %v", err) } if q.Matches(&farEv) { t.Fatal("the query matches a batch outside its range") } } // TestAddStopsAtTheBudget: the body budget is a hard limit, and the filter that // does not fit must be left for the next batch rather than dropped or // truncated. func TestAddStopsAtTheBudget(t *testing.T) { b := &Batch{Chain: "btc", From: 1, At: 1750000000} filter := make([]byte, 4096) per := EntryOverhead + len(filter) want := BodySize / per var n int for { if err := b.Add(chainhash.DoubleHashH(filter), filter); err != nil { if !errors.Is(err, ErrFull) { t.Fatalf("add: %v", err) } break } n++ } if n != want { t.Fatalf("filled %d filters, want %d", n, want) } if b.Len() != want || len(b.Hashes) != want { t.Fatalf("batch holds %d filters and %d hashes, want %d of each", b.Len(), len(b.Hashes), want) } // The batch that stopped must still encode under the event cap. ev, err := b.Encode() if err != nil { t.Fatalf("encode full batch: %v", err) } if len(ev.Content) > MaxContent { t.Fatalf("content is %d bytes, cap is %d", len(ev.Content), MaxContent) } } // TestKindIsRegular: the batch kind must not be addressable or ephemeral. An // addressable kind is stored per (kind, pubkey, d-tag), so every batch one // producer publishes replaces the last one: the relay keeps a single batch and // answers "replaced" for all the others. func TestKindIsRegular(t *testing.T) { ev := nostr.Event{Kind: Kind} if ev.IsAddressable() { t.Fatalf("kind %d is addressable, so batches would replace each other", Kind) } if ev.IsEphemeral() { t.Fatalf("kind %d is ephemeral, so nothing would be stored", Kind) } if ev.IsReplaceable() { t.Fatalf("kind %d is replaceable, so one batch would replace the last", Kind) } } // TestDecodeRejectsKind: the kind is the only thing that identifies the format, // so an event of another kind must not parse as a batch. func TestDecodeRejectsKind(t *testing.T) { ev := nostr.Event{Kind: Kind + 1, CreatedAt: 1, Content: ""} if _, err := Decode(&ev); err == nil { t.Fatal("decoded an event of the wrong kind") } }