package main import ( "context" "errors" "fmt" "path/filepath" "strings" "testing" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/cfevents" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/nostr" "git.smesh.lol/nostrino/pkg/relay" ) // fakeNode is a chain whose filters are whatever the test says, so the loop can // be driven without a node. type fakeNode struct { tipHeight uint32 size func(uint32) int heights map[chainhash.Hash]uint32 } func newFakeNode(tip uint32, size func(uint32) int) *fakeNode { return &fakeNode{tipHeight: tip, size: size, heights: map[chainhash.Hash]uint32{}} } func (f *fakeNode) hash(height uint32) chainhash.Hash { return chainhash.HashH([]byte(fmt.Sprintf("block-%d", height))) } func (f *fakeNode) tip(context.Context) (uint32, error) { return f.tipHeight, nil } // header exists so the fixture satisfies the node interface. The fixture's block hashes are // arbitrary strings rather than mined headers, so it cannot produce a header that hashes to // one; the tests that use it run with header publishing off. func (f *fakeNode) header(context.Context, uint32) (btcwire.BlockHeader, error) { return btcwire.BlockHeader{}, errors.New("the fixture has no headers") } func (f *fakeNode) register(height uint32) chainhash.Hash { hash := f.hash(height) f.heights[hash] = height return hash } // block is the publisher's read by height. The fixture's blocks are not chain data, so only the // header path is real; a test that needs a block uses a stub reader instead. func (f *fakeNode) block(_ context.Context, height uint32) ([]byte, error) { return nil, errors.New("the fixture has no blocks") } func (f *fakeNode) blockByHash(context.Context, chainhash.Hash) ([]byte, error) { return nil, errors.New("the fixture has no blocks") } func (f *fakeNode) blockTime(_ context.Context, height uint32) (int64, error) { return 1700000000 + int64(height)*600, nil } func (f *fakeNode) filter(_ context.Context, height uint32) ([]byte, chainhash.Hash, error) { filter := make([]byte, f.size(height)) for i := range filter { filter[i] = byte(height) + byte(i) } return filter, chainhash.DoubleHashH(filter), nil } // recordingSink keeps the events a run published. type recordingSink struct { events []*nostr.Event } func (r *recordingSink) publish(_ context.Context, ev *nostr.Event) error { ev.ComputeID() r.events = append(r.events, ev) return nil } // ranges decodes each published event's height range. func ranges(t *testing.T, events []*nostr.Event) [][2]uint32 { t.Helper() out := make([][2]uint32, 0, len(events)) for i, ev := range events { batch, err := cfevents.Decode(ev) if err != nil { t.Fatalf("event %d does not decode: %v", i, err) } out = append(out, [2]uint32{batch.From, batch.To()}) } return out } // cfgFor is the smallest configuration the loop needs. func cfgFor(from uint32) *config { return &config{ chain: &chain.Bitcoin, from: from, once: true, attempts: 3, } } // fakeSink answers with the given errors, then accepts. type fakeSink struct { errs []error calls int } func (f *fakeSink) publish(context.Context, *nostr.Event) error { f.calls++ if len(f.errs) == 0 { return nil } err := f.errs[0] f.errs = f.errs[1:] return err } // TestPermanentRefusalIsNotRetried: a relay that refuses on policy will refuse // on the second attempt too, and eight rounds of backoff only delay the // operator reading the reason. func TestPermanentRefusalIsNotRetried(t *testing.T) { sink := &fakeSink{errs: []error{&refused{ url: "wss://relay", Rejection: &relay.Rejection{Reason: "blocked: this key is not registered to publish this kind"}, }}} ev := nostr.Event{Kind: cfevents.Kind, CreatedAt: 1700000000} err := publishWithRetry(context.Background(), sink, &ev, 8) if err == nil { t.Fatal("a permanent refusal was reported as success") } if sink.calls != 1 { t.Fatalf("the event was published %d times, want 1", sink.calls) } if !strings.Contains(err.Error(), "permanently") { t.Fatalf("the error does not say the refusal was permanent: %v", err) } } // TestBusyRelayIsRetried: a rate limit or a dropped connection clears on its // own, so the same event goes out again. func TestBusyRelayIsRetried(t *testing.T) { sink := &fakeSink{errs: []error{ errors.New("wss://relay: relay: closed"), errors.New("wss://relay: relay: closed"), }} ev := nostr.Event{Kind: cfevents.Kind, CreatedAt: 1700000000} if err := publishWithRetry(context.Background(), sink, &ev, 3); err != nil { t.Fatalf("a retryable failure was not retried to success: %v", err) } if sink.calls != 3 { t.Fatalf("the event went out %d times, want 3", sink.calls) } } // TestBatchesTileTheRangeWithoutGaps: the cache is only usable if every height // from the floor to the tip is in exactly one event. A repeat wastes a relay // slot; a gap is a height every client falls back for, and one nobody notices. func TestBatchesTileTheRangeWithoutGaps(t *testing.T) { const from, tip = 900, 950 node := newFakeNode(tip, func(uint32) int { return 4096 }) sink := &recordingSink{} st := &state{Chain: "btc", Start: from, PublishedTo: int64(from) - 1} path := filepath.Join(t.TempDir(), "state.json") if err := follow(context.Background(), cfgFor(from), node, sink, st, path, nil); err != nil { t.Fatalf("follow: %v", err) } got := ranges(t, sink.events) if len(got) == 0 { t.Fatal("nothing was published") } want := uint32(from) for i, r := range got { if r[0] != want { t.Fatalf("batch %d starts at %d, want %d (batches %v)", i, r[0], want, got) } if r[1] < r[0] { t.Fatalf("batch %d is reversed: %v", i, r) } want = r[1] + 1 } if want != tip+1 { t.Fatalf("coverage ends at %d, want %d (batches %v)", want-1, tip, got) } if st.PublishedTo != int64(tip) { t.Fatalf("state says published to %d, want %d", st.PublishedTo, tip) } } // TestRestartPublishesNothingAlreadyPublished: a restart resumes at the // watermark. Without that, the program rebuilds the same batches forever and // every one of them costs a relay round trip to be told it is a duplicate. func TestRestartPublishesNothingAlreadyPublished(t *testing.T) { const from, tip = 961631, 961700 node := newFakeNode(tip, func(uint32) int { return 20000 }) path := filepath.Join(t.TempDir(), "state.json") st := &state{Chain: "btc", Start: from, PublishedTo: int64(from) - 1} first := &recordingSink{} if err := follow(context.Background(), cfgFor(from), node, first, st, path, nil); err != nil { t.Fatalf("first run: %v", err) } if len(first.events) == 0 { t.Fatal("the first run published nothing") } reloaded, err := loadState(path) if err != nil { t.Fatalf("load state: %v", err) } if reloaded == nil || reloaded.PublishedTo != int64(tip) { t.Fatalf("state after the first run: %+v, want published_to %d", reloaded, tip) } second := &recordingSink{} if err := follow(context.Background(), cfgFor(from), node, second, reloaded, path, nil); err != nil { t.Fatalf("second run: %v", err) } if len(second.events) != 0 { t.Fatalf("the restart republished %d batches", len(second.events)) } } // TestSameRangeSameIDs: the event id has to depend on the chain and not on when // the program ran, or a restart would put a second copy of every batch in the // relay instead of being answered "duplicate". func TestSameRangeSameIDs(t *testing.T) { const from, tip = 961631, 961800 node := newFakeNode(tip, func(height uint32) int { return 8000 + int(height%7)*300 }) cfg := cfgFor(from) run := func() []*nostr.Event { t.Helper() sink := &recordingSink{} st := &state{Chain: "btc", Start: from, PublishedTo: int64(from) - 1} path := filepath.Join(t.TempDir(), "state.json") if err := follow(context.Background(), cfg, node, sink, st, path, nil); err != nil { t.Fatalf("follow: %v", err) } return sink.events } first, second := run(), run() if len(first) != len(second) { t.Fatalf("two runs published %d and %d batches", len(first), len(second)) } for i := range first { if first[i].ID != second[i].ID { t.Fatalf("batch %d has id %s on one run and %s on the next", i, nostr.Hex(first[i].ID[:]), nostr.Hex(second[i].ID[:])) } } } // TestBatchRespectsTheContentCap: a batch that encodes past the limit is one the // relay refuses, and a producer that only finds out at publish time stalls the // whole backfill on one oversized block. func TestBatchRespectsTheContentCap(t *testing.T) { const from, tip = 100, 400 node := newFakeNode(tip, func(uint32) int { return 40000 }) batch, err := build(context.Background(), node, "btc", from, tip) if err != nil { t.Fatalf("build: %v", err) } ev, err := batch.Encode() if err != nil { t.Fatalf("encode: %v", err) } if len(ev.Content) > cfevents.MaxContent { t.Fatalf("content is %d bytes, the cap is %d", len(ev.Content), cfevents.MaxContent) } } // TestTheTagDefaultsToTheNameAskedFor: a client addresses a chain by the name it knows, and the // profile only supplies the parameters. Starting the sidecar with the application's spelling // must publish under that spelling, or a head asking for blake reads nothing. func TestTheTagDefaultsToTheNameAskedFor(t *testing.T) { cfg, err := parseFlags([]string{ "-node", "http://127.0.0.1:8332", "-chain", "blake", "-relay", "ws://relay:3337", }) if err != nil { t.Fatal(err) } if cfg.tag != "blake" { t.Fatalf("tag = %q, want the name that was asked for", cfg.tag) } if cfg.chain.Name != "xbt" { t.Fatalf("profile = %q, want the blake profile", cfg.chain.Name) } explicit, err := parseFlags([]string{ "-node", "http://127.0.0.1:8332", "-chain", "regtest", "-tag", "btc", "-relay", "ws://relay:3337", }) if err != nil { t.Fatal(err) } if explicit.tag != "btc" { t.Fatalf("explicit tag = %q", explicit.tag) } }