cfevents_test.go raw

   1  package cfevents
   2  
   3  import (
   4  	"encoding/base64"
   5  	"errors"
   6  	"testing"
   7  
   8  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
   9  	"git.smesh.lol/nostrino/pkg/nostr"
  10  )
  11  
  12  // batch builds a batch of n filters at From, with hashes that match the filter
  13  // bytes, which is what a correct producer publishes.
  14  func batch(from uint32, sizes ...int) *Batch {
  15  	b := &Batch{Chain: "btc", From: from, At: 1750000000}
  16  	for i, n := range sizes {
  17  		filter := make([]byte, n)
  18  		for j := range filter {
  19  			filter[j] = byte(i*7 + j*13)
  20  		}
  21  		if err := b.Add(chainhash.DoubleHashH(filter), filter); err != nil {
  22  			panic(err)
  23  		}
  24  	}
  25  	return b
  26  }
  27  
  28  // committedFor returns the committed-hash lookup a client with a matching store
  29  // would provide.
  30  func committedFor(b *Batch) func(uint32) (chainhash.Hash, bool) {
  31  	return func(h uint32) (chainhash.Hash, bool) {
  32  		i := int(h) - int(b.From)
  33  		if i < 0 || i >= len(b.Hashes) {
  34  			return chainhash.Hash{}, false
  35  		}
  36  		return b.Hashes[i], true
  37  	}
  38  }
  39  
  40  // TestRoundTrip: what the producer encodes is what the consumer decodes, tags
  41  // and bytes included. The event id is stable for the same batch, which is what
  42  // makes a republished batch cost a duplicate answer instead of a second event.
  43  func TestRoundTrip(t *testing.T) {
  44  	orig := batch(961631, 900, 1200, 40)
  45  	ev, err := orig.Encode()
  46  	if err != nil {
  47  		t.Fatalf("encode: %v", err)
  48  	}
  49  	ev.Sign([32]byte{1, 2, 3})
  50  	firstID := ev.ID
  51  
  52  	got, err := Decode(&ev)
  53  	if err != nil {
  54  		t.Fatalf("decode: %v", err)
  55  	}
  56  
  57  	if got.Chain != orig.Chain || got.From != orig.From || got.To() != orig.To() || got.At != orig.At {
  58  		t.Fatalf("header differs: got %+v, want chain=%s from=%d to=%d at=%d",
  59  			got, orig.Chain, orig.From, orig.To(), orig.At)
  60  	}
  61  	if len(got.Filters) != len(orig.Filters) {
  62  		t.Fatalf("got %d filters, want %d", len(got.Filters), len(orig.Filters))
  63  	}
  64  	for i := range orig.Filters {
  65  		if string(got.Filters[i]) != string(orig.Filters[i]) {
  66  			t.Fatalf("filter %d differs", i)
  67  		}
  68  		if got.Hashes[i] != orig.Hashes[i] {
  69  			t.Fatalf("hash %d differs", i)
  70  		}
  71  	}
  72  
  73  	// Re-encoding the same batch must produce the same id, or a restarted
  74  	// producer would grow the relay's store instead of hitting a duplicate.
  75  	again, err := got.Encode()
  76  	if err != nil {
  77  		t.Fatalf("re-encode: %v", err)
  78  	}
  79  	again.Sign([32]byte{1, 2, 3})
  80  	if again.ID != firstID {
  81  		t.Fatal("the same batch encoded to a different event id")
  82  	}
  83  }
  84  
  85  // TestTakeRejectsWrongFilter: a batch whose bytes do not hash to the hash it
  86  // carries must not be stored. The height is left out of the result so the
  87  // consumer fetches it from a peer.
  88  func TestTakeRejectsWrongFilter(t *testing.T) {
  89  	orig := batch(100, 500, 600)
  90  	ev, err := orig.Encode()
  91  	if err != nil {
  92  		t.Fatalf("encode: %v", err)
  93  	}
  94  
  95  	// Corrupt one filter without touching its hash, the way a producer bug or a
  96  	// tampering relay would.
  97  	body, err := base64.StdEncoding.DecodeString(ev.Content)
  98  	if err != nil {
  99  		t.Fatalf("decode body: %v", err)
 100  	}
 101  	body[len(body)-1] ^= 0xff
 102  	ev.Content = base64.StdEncoding.EncodeToString(body)
 103  
 104  	got, err := Decode(&ev)
 105  	if err != nil {
 106  		t.Fatalf("decode: %v", err)
 107  	}
 108  	taken, err := got.Take(committedFor(orig))
 109  	if err != nil {
 110  		t.Fatalf("take: %v", err)
 111  	}
 112  	if len(taken) != 1 {
 113  		t.Fatalf("took %d filters, want 1", len(taken))
 114  	}
 115  	if _, ok := taken[100]; !ok {
 116  		t.Fatalf("the untouched filter was dropped: %v", taken)
 117  	}
 118  	if _, ok := taken[101]; ok {
 119  		t.Fatal("the corrupted filter was stored")
 120  	}
 121  }
 122  
 123  // TestTakeRejectsWrongChain: when the first filter hash is not the committed
 124  // one the batch is for another chain or a fork, and none of it may be stored.
 125  func TestTakeRejectsWrongChain(t *testing.T) {
 126  	orig := batch(100, 500, 600)
 127  	ev, err := orig.Encode()
 128  	if err != nil {
 129  		t.Fatalf("encode: %v", err)
 130  	}
 131  	got, err := Decode(&ev)
 132  	if err != nil {
 133  		t.Fatalf("decode: %v", err)
 134  	}
 135  
 136  	other := func(uint32) (chainhash.Hash, bool) { return chainhash.HashH([]byte("other")), true }
 137  	if _, err := got.Take(other); err == nil {
 138  		t.Fatal("a batch from another chain was accepted")
 139  	}
 140  }
 141  
 142  // TestTakeWithoutCommitment: a consumer with no filter hash at that height
 143  // cannot judge the batch, so it gets nothing and no error. That is the range it
 144  // has not synced yet, and the peer answers it as it always did.
 145  func TestTakeWithoutCommitment(t *testing.T) {
 146  	got := batch(100, 500)
 147  	taken, err := got.Take(func(uint32) (chainhash.Hash, bool) { return chainhash.Hash{}, false })
 148  	if err != nil {
 149  		t.Fatalf("take: %v", err)
 150  	}
 151  	if len(taken) != 0 {
 152  		t.Fatalf("took %d filters with no commitment", len(taken))
 153  	}
 154  }
 155  
 156  // TestDecodeRejectsTruncatedBody: a body that ends inside a filter must be an
 157  // error, not a short batch. Reading past what arrived is how a decoder turns
 158  // into a random number generator.
 159  func TestDecodeRejectsTruncatedBody(t *testing.T) {
 160  	orig := batch(100, 500, 600)
 161  	ev, err := orig.Encode()
 162  	if err != nil {
 163  		t.Fatalf("encode: %v", err)
 164  	}
 165  	body, err := base64.StdEncoding.DecodeString(ev.Content)
 166  	if err != nil {
 167  		t.Fatalf("decode body: %v", err)
 168  	}
 169  
 170  	for _, cut := range []int{0, 2, 4, 10, len(body) / 2, len(body) - 1} {
 171  		ev.Content = base64.StdEncoding.EncodeToString(body[:cut])
 172  		if _, err := Decode(&ev); err == nil {
 173  			t.Fatalf("decoded a body truncated to %d of %d bytes", cut, len(body))
 174  		}
 175  	}
 176  }
 177  
 178  // TestDecodeRejectsTagMismatch: the tags say how many filters the body holds.
 179  // A batch whose tags and body disagree is malformed, and a consumer that
 180  // trusted either one alone would store filters at the wrong heights.
 181  func TestDecodeRejectsTagMismatch(t *testing.T) {
 182  	orig := batch(100, 500, 600)
 183  	ev, err := orig.Encode()
 184  	if err != nil {
 185  		t.Fatalf("encode: %v", err)
 186  	}
 187  	for i, tag := range ev.Tags {
 188  		if tag.Name() == "to" {
 189  			ev.Tags[i] = nostr.Tag{"to", "102"}
 190  		}
 191  	}
 192  	if _, err := Decode(&ev); err == nil {
 193  		t.Fatal("decoded a batch whose tag range exceeds its body")
 194  	}
 195  }
 196  
 197  // TestQueryNamesEveryHeight: the query is what a consumer sends to find a
 198  // batch, and a relay matches tag values exactly. A query that named only the
 199  // ends of the range would return nothing, because no event carries a tag for
 200  // "anything between 900 and 950".
 201  func TestQueryNamesEveryHeight(t *testing.T) {
 202  	q := Query("btc", 900, 950)
 203  	if len(q.Tags[HeightTag]) != 51 {
 204  		t.Fatalf("query names %d heights, want 51", len(q.Tags[HeightTag]))
 205  	}
 206  	if q.Tags[HeightTag][0] != "900" || q.Tags[HeightTag][50] != "950" {
 207  		t.Fatalf("query heights run %s..%s", q.Tags[HeightTag][0], q.Tags[HeightTag][50])
 208  	}
 209  	if len(q.Tags[ChainTag]) != 1 || q.Tags[ChainTag][0] != "btc" {
 210  		t.Fatalf("query chain is %v", q.Tags[ChainTag])
 211  	}
 212  	if q.Limit != 51 {
 213  		t.Fatalf("query limit is %d, want 51", q.Limit)
 214  	}
 215  
 216  	// The query has to match the events the producer writes, or the cache is
 217  	// unreachable no matter how correct the filters are.
 218  	b := batch(900, 100, 100)
 219  	ev, err := b.Encode()
 220  	if err != nil {
 221  		t.Fatalf("encode: %v", err)
 222  	}
 223  	if !q.Matches(&ev) {
 224  		t.Fatal("the query does not match a batch it was built for")
 225  	}
 226  
 227  	other := batch(950, 100)
 228  	otherEv, err := other.Encode()
 229  	if err != nil {
 230  		t.Fatalf("encode: %v", err)
 231  	}
 232  	if !q.Matches(&otherEv) {
 233  		t.Fatal("the query does not match a batch that covers its last height")
 234  	}
 235  
 236  	far := batch(1000, 100)
 237  	farEv, err := far.Encode()
 238  	if err != nil {
 239  		t.Fatalf("encode: %v", err)
 240  	}
 241  	if q.Matches(&farEv) {
 242  		t.Fatal("the query matches a batch outside its range")
 243  	}
 244  }
 245  
 246  // TestAddStopsAtTheBudget: the body budget is a hard limit, and the filter that
 247  // does not fit must be left for the next batch rather than dropped or
 248  // truncated.
 249  func TestAddStopsAtTheBudget(t *testing.T) {
 250  	b := &Batch{Chain: "btc", From: 1, At: 1750000000}
 251  	filter := make([]byte, 4096)
 252  	per := EntryOverhead + len(filter)
 253  	want := BodySize / per
 254  
 255  	var n int
 256  	for {
 257  		if err := b.Add(chainhash.DoubleHashH(filter), filter); err != nil {
 258  			if !errors.Is(err, ErrFull) {
 259  				t.Fatalf("add: %v", err)
 260  			}
 261  			break
 262  		}
 263  		n++
 264  	}
 265  	if n != want {
 266  		t.Fatalf("filled %d filters, want %d", n, want)
 267  	}
 268  	if b.Len() != want || len(b.Hashes) != want {
 269  		t.Fatalf("batch holds %d filters and %d hashes, want %d of each", b.Len(), len(b.Hashes), want)
 270  	}
 271  	// The batch that stopped must still encode under the event cap.
 272  	ev, err := b.Encode()
 273  	if err != nil {
 274  		t.Fatalf("encode full batch: %v", err)
 275  	}
 276  	if len(ev.Content) > MaxContent {
 277  		t.Fatalf("content is %d bytes, cap is %d", len(ev.Content), MaxContent)
 278  	}
 279  }
 280  
 281  // TestKindIsRegular: the batch kind must not be addressable or ephemeral. An
 282  // addressable kind is stored per (kind, pubkey, d-tag), so every batch one
 283  // producer publishes replaces the last one: the relay keeps a single batch and
 284  // answers "replaced" for all the others.
 285  func TestKindIsRegular(t *testing.T) {
 286  	ev := nostr.Event{Kind: Kind}
 287  
 288  	if ev.IsAddressable() {
 289  		t.Fatalf("kind %d is addressable, so batches would replace each other", Kind)
 290  	}
 291  
 292  	if ev.IsEphemeral() {
 293  		t.Fatalf("kind %d is ephemeral, so nothing would be stored", Kind)
 294  	}
 295  
 296  	if ev.IsReplaceable() {
 297  		t.Fatalf("kind %d is replaceable, so one batch would replace the last", Kind)
 298  	}
 299  }
 300  
 301  // TestDecodeRejectsKind: the kind is the only thing that identifies the format,
 302  // so an event of another kind must not parse as a batch.
 303  func TestDecodeRejectsKind(t *testing.T) {
 304  	ev := nostr.Event{Kind: Kind + 1, CreatedAt: 1, Content: ""}
 305  	if _, err := Decode(&ev); err == nil {
 306  		t.Fatal("decoded an event of the wrong kind")
 307  	}
 308  }
 309