main_test.go raw

   1  package main
   2  
   3  import (
   4  	"context"
   5  	"errors"
   6  	"fmt"
   7  	"path/filepath"
   8  	"strings"
   9  	"testing"
  10  
  11  	"git.smesh.lol/nostrino/pkg/btcwire"
  12  	"git.smesh.lol/nostrino/pkg/cfevents"
  13  	"git.smesh.lol/nostrino/pkg/chain"
  14  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  15  	"git.smesh.lol/nostrino/pkg/nostr"
  16  	"git.smesh.lol/nostrino/pkg/relay"
  17  )
  18  
  19  // fakeNode is a chain whose filters are whatever the test says, so the loop can
  20  // be driven without a node.
  21  type fakeNode struct {
  22  	tipHeight uint32
  23  	size      func(uint32) int
  24  	heights   map[chainhash.Hash]uint32
  25  }
  26  
  27  func newFakeNode(tip uint32, size func(uint32) int) *fakeNode {
  28  	return &fakeNode{tipHeight: tip, size: size, heights: map[chainhash.Hash]uint32{}}
  29  }
  30  
  31  func (f *fakeNode) hash(height uint32) chainhash.Hash {
  32  	return chainhash.HashH([]byte(fmt.Sprintf("block-%d", height)))
  33  }
  34  
  35  func (f *fakeNode) tip(context.Context) (uint32, error) { return f.tipHeight, nil }
  36  
  37  // header exists so the fixture satisfies the node interface. The fixture's block hashes are
  38  // arbitrary strings rather than mined headers, so it cannot produce a header that hashes to
  39  // one; the tests that use it run with header publishing off.
  40  func (f *fakeNode) header(context.Context, uint32) (btcwire.BlockHeader, error) {
  41  	return btcwire.BlockHeader{}, errors.New("the fixture has no headers")
  42  }
  43  
  44  func (f *fakeNode) register(height uint32) chainhash.Hash {
  45  	hash := f.hash(height)
  46  	f.heights[hash] = height
  47  
  48  	return hash
  49  }
  50  
  51  // block is the publisher's read by height. The fixture's blocks are not chain data, so only the
  52  // header path is real; a test that needs a block uses a stub reader instead.
  53  func (f *fakeNode) block(_ context.Context, height uint32) ([]byte, error) {
  54  	return nil, errors.New("the fixture has no blocks")
  55  }
  56  
  57  func (f *fakeNode) blockByHash(context.Context, chainhash.Hash) ([]byte, error) {
  58  	return nil, errors.New("the fixture has no blocks")
  59  }
  60  
  61  func (f *fakeNode) blockTime(_ context.Context, height uint32) (int64, error) {
  62  	return 1700000000 + int64(height)*600, nil
  63  }
  64  
  65  func (f *fakeNode) filter(_ context.Context, height uint32) ([]byte, chainhash.Hash, error) {
  66  	filter := make([]byte, f.size(height))
  67  	for i := range filter {
  68  		filter[i] = byte(height) + byte(i)
  69  	}
  70  	return filter, chainhash.DoubleHashH(filter), nil
  71  }
  72  
  73  // recordingSink keeps the events a run published.
  74  type recordingSink struct {
  75  	events []*nostr.Event
  76  }
  77  
  78  func (r *recordingSink) publish(_ context.Context, ev *nostr.Event) error {
  79  	ev.ComputeID()
  80  	r.events = append(r.events, ev)
  81  	return nil
  82  }
  83  
  84  // ranges decodes each published event's height range.
  85  func ranges(t *testing.T, events []*nostr.Event) [][2]uint32 {
  86  	t.Helper()
  87  	out := make([][2]uint32, 0, len(events))
  88  	for i, ev := range events {
  89  		batch, err := cfevents.Decode(ev)
  90  		if err != nil {
  91  			t.Fatalf("event %d does not decode: %v", i, err)
  92  		}
  93  		out = append(out, [2]uint32{batch.From, batch.To()})
  94  	}
  95  	return out
  96  }
  97  
  98  // cfgFor is the smallest configuration the loop needs.
  99  func cfgFor(from uint32) *config {
 100  	return &config{
 101  		chain:    &chain.Bitcoin,
 102  		from:     from,
 103  		once:     true,
 104  		attempts: 3,
 105  	}
 106  }
 107  
 108  // fakeSink answers with the given errors, then accepts.
 109  type fakeSink struct {
 110  	errs  []error
 111  	calls int
 112  }
 113  
 114  func (f *fakeSink) publish(context.Context, *nostr.Event) error {
 115  	f.calls++
 116  
 117  	if len(f.errs) == 0 {
 118  		return nil
 119  	}
 120  
 121  	err := f.errs[0]
 122  	f.errs = f.errs[1:]
 123  
 124  	return err
 125  }
 126  
 127  // TestPermanentRefusalIsNotRetried: a relay that refuses on policy will refuse
 128  // on the second attempt too, and eight rounds of backoff only delay the
 129  // operator reading the reason.
 130  func TestPermanentRefusalIsNotRetried(t *testing.T) {
 131  	sink := &fakeSink{errs: []error{&refused{
 132  		url:       "wss://relay",
 133  		Rejection: &relay.Rejection{Reason: "blocked: this key is not registered to publish this kind"},
 134  	}}}
 135  
 136  	ev := nostr.Event{Kind: cfevents.Kind, CreatedAt: 1700000000}
 137  
 138  	err := publishWithRetry(context.Background(), sink, &ev, 8)
 139  	if err == nil {
 140  		t.Fatal("a permanent refusal was reported as success")
 141  	}
 142  
 143  	if sink.calls != 1 {
 144  		t.Fatalf("the event was published %d times, want 1", sink.calls)
 145  	}
 146  
 147  	if !strings.Contains(err.Error(), "permanently") {
 148  		t.Fatalf("the error does not say the refusal was permanent: %v", err)
 149  	}
 150  }
 151  
 152  // TestBusyRelayIsRetried: a rate limit or a dropped connection clears on its
 153  // own, so the same event goes out again.
 154  func TestBusyRelayIsRetried(t *testing.T) {
 155  	sink := &fakeSink{errs: []error{
 156  		errors.New("wss://relay: relay: closed"),
 157  		errors.New("wss://relay: relay: closed"),
 158  	}}
 159  
 160  	ev := nostr.Event{Kind: cfevents.Kind, CreatedAt: 1700000000}
 161  
 162  	if err := publishWithRetry(context.Background(), sink, &ev, 3); err != nil {
 163  		t.Fatalf("a retryable failure was not retried to success: %v", err)
 164  	}
 165  
 166  	if sink.calls != 3 {
 167  		t.Fatalf("the event went out %d times, want 3", sink.calls)
 168  	}
 169  }
 170  
 171  // TestBatchesTileTheRangeWithoutGaps: the cache is only usable if every height
 172  // from the floor to the tip is in exactly one event. A repeat wastes a relay
 173  // slot; a gap is a height every client falls back for, and one nobody notices.
 174  func TestBatchesTileTheRangeWithoutGaps(t *testing.T) {
 175  	const from, tip = 900, 950
 176  	node := newFakeNode(tip, func(uint32) int { return 4096 })
 177  	sink := &recordingSink{}
 178  	st := &state{Chain: "btc", Start: from, PublishedTo: int64(from) - 1}
 179  	path := filepath.Join(t.TempDir(), "state.json")
 180  
 181  	if err := follow(context.Background(), cfgFor(from), node, sink, st, path, nil); err != nil {
 182  		t.Fatalf("follow: %v", err)
 183  	}
 184  
 185  	got := ranges(t, sink.events)
 186  	if len(got) == 0 {
 187  		t.Fatal("nothing was published")
 188  	}
 189  	want := uint32(from)
 190  	for i, r := range got {
 191  		if r[0] != want {
 192  			t.Fatalf("batch %d starts at %d, want %d (batches %v)", i, r[0], want, got)
 193  		}
 194  		if r[1] < r[0] {
 195  			t.Fatalf("batch %d is reversed: %v", i, r)
 196  		}
 197  		want = r[1] + 1
 198  	}
 199  	if want != tip+1 {
 200  		t.Fatalf("coverage ends at %d, want %d (batches %v)", want-1, tip, got)
 201  	}
 202  	if st.PublishedTo != int64(tip) {
 203  		t.Fatalf("state says published to %d, want %d", st.PublishedTo, tip)
 204  	}
 205  }
 206  
 207  // TestRestartPublishesNothingAlreadyPublished: a restart resumes at the
 208  // watermark. Without that, the program rebuilds the same batches forever and
 209  // every one of them costs a relay round trip to be told it is a duplicate.
 210  func TestRestartPublishesNothingAlreadyPublished(t *testing.T) {
 211  	const from, tip = 961631, 961700
 212  	node := newFakeNode(tip, func(uint32) int { return 20000 })
 213  	path := filepath.Join(t.TempDir(), "state.json")
 214  	st := &state{Chain: "btc", Start: from, PublishedTo: int64(from) - 1}
 215  
 216  	first := &recordingSink{}
 217  	if err := follow(context.Background(), cfgFor(from), node, first, st, path, nil); err != nil {
 218  		t.Fatalf("first run: %v", err)
 219  	}
 220  	if len(first.events) == 0 {
 221  		t.Fatal("the first run published nothing")
 222  	}
 223  
 224  	reloaded, err := loadState(path)
 225  	if err != nil {
 226  		t.Fatalf("load state: %v", err)
 227  	}
 228  	if reloaded == nil || reloaded.PublishedTo != int64(tip) {
 229  		t.Fatalf("state after the first run: %+v, want published_to %d", reloaded, tip)
 230  	}
 231  
 232  	second := &recordingSink{}
 233  	if err := follow(context.Background(), cfgFor(from), node, second, reloaded, path, nil); err != nil {
 234  		t.Fatalf("second run: %v", err)
 235  	}
 236  	if len(second.events) != 0 {
 237  		t.Fatalf("the restart republished %d batches", len(second.events))
 238  	}
 239  }
 240  
 241  // TestSameRangeSameIDs: the event id has to depend on the chain and not on when
 242  // the program ran, or a restart would put a second copy of every batch in the
 243  // relay instead of being answered "duplicate".
 244  func TestSameRangeSameIDs(t *testing.T) {
 245  	const from, tip = 961631, 961800
 246  	node := newFakeNode(tip, func(height uint32) int { return 8000 + int(height%7)*300 })
 247  	cfg := cfgFor(from)
 248  
 249  	run := func() []*nostr.Event {
 250  		t.Helper()
 251  		sink := &recordingSink{}
 252  		st := &state{Chain: "btc", Start: from, PublishedTo: int64(from) - 1}
 253  		path := filepath.Join(t.TempDir(), "state.json")
 254  		if err := follow(context.Background(), cfg, node, sink, st, path, nil); err != nil {
 255  			t.Fatalf("follow: %v", err)
 256  		}
 257  		return sink.events
 258  	}
 259  
 260  	first, second := run(), run()
 261  	if len(first) != len(second) {
 262  		t.Fatalf("two runs published %d and %d batches", len(first), len(second))
 263  	}
 264  	for i := range first {
 265  		if first[i].ID != second[i].ID {
 266  			t.Fatalf("batch %d has id %s on one run and %s on the next",
 267  				i, nostr.Hex(first[i].ID[:]), nostr.Hex(second[i].ID[:]))
 268  		}
 269  	}
 270  }
 271  
 272  // TestBatchRespectsTheContentCap: a batch that encodes past the limit is one the
 273  // relay refuses, and a producer that only finds out at publish time stalls the
 274  // whole backfill on one oversized block.
 275  func TestBatchRespectsTheContentCap(t *testing.T) {
 276  	const from, tip = 100, 400
 277  	node := newFakeNode(tip, func(uint32) int { return 40000 })
 278  	batch, err := build(context.Background(), node, "btc", from, tip)
 279  	if err != nil {
 280  		t.Fatalf("build: %v", err)
 281  	}
 282  	ev, err := batch.Encode()
 283  	if err != nil {
 284  		t.Fatalf("encode: %v", err)
 285  	}
 286  	if len(ev.Content) > cfevents.MaxContent {
 287  		t.Fatalf("content is %d bytes, the cap is %d", len(ev.Content), cfevents.MaxContent)
 288  	}
 289  }
 290  
 291  // TestTheTagDefaultsToTheNameAskedFor: a client addresses a chain by the name it knows, and the
 292  // profile only supplies the parameters. Starting the sidecar with the application's spelling
 293  // must publish under that spelling, or a head asking for blake reads nothing.
 294  func TestTheTagDefaultsToTheNameAskedFor(t *testing.T) {
 295  	cfg, err := parseFlags([]string{
 296  		"-node", "http://127.0.0.1:8332", "-chain", "blake",
 297  		"-relay", "ws://relay:3337",
 298  	})
 299  
 300  	if err != nil {
 301  		t.Fatal(err)
 302  	}
 303  
 304  	if cfg.tag != "blake" {
 305  		t.Fatalf("tag = %q, want the name that was asked for", cfg.tag)
 306  	}
 307  
 308  	if cfg.chain.Name != "xbt" {
 309  		t.Fatalf("profile = %q, want the blake profile", cfg.chain.Name)
 310  	}
 311  
 312  	explicit, err := parseFlags([]string{
 313  		"-node", "http://127.0.0.1:8332", "-chain", "regtest", "-tag", "btc",
 314  		"-relay", "ws://relay:3337",
 315  	})
 316  
 317  	if err != nil {
 318  		t.Fatal(err)
 319  	}
 320  
 321  	if explicit.tag != "btc" {
 322  		t.Fatalf("explicit tag = %q", explicit.tag)
 323  	}
 324  }
 325