package neutrino import ( "context" "testing" "time" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // TestHeadersArriveFromTheSourceWithoutAPeer is the shape the relay header path has to have: // a store anchored at a checkpoint, a source that holds the next run of headers, and no peer // at all. The peer address in this client is a dead one, so the sync only succeeds if the // source carried it to the tip and the failed dial is treated as "nothing more to fetch". func TestHeadersArriveFromTheSourceWithoutAPeer(t *testing.T) { profile := chain.Regtest store := NewMemory() tip := seedHeaders(t, &profile, store, 5, 600) // The run the source holds: five headers mined on top of the stored tip. run := make([]btcwire.BlockHeader, 0, 5) prev := tip for i := 1; i <= 5; i++ { header := mineAt(t, prev, profile.GenesisHeader.Timestamp+600*uint32(5+i), profile.PowLimitBits, byte(0xa0+i)) run = append(run, header) prev = header.BlockHash() } calls := 0 client := testClient(t, &profile, store) client.cfg.HeaderSource = func(_ context.Context, from, to uint32) ([]btcwire.BlockHeader, error) { calls++ if from != 6 { t.Fatalf("source asked for %d..%d, want the run from 6", from, to) } return run, nil } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() added, err := client.SyncHeaders(ctx) if err != nil { t.Fatalf("a source that carried the chain to its tip was reported as a failure: %v", err) } if added != 5 { t.Fatalf("added %d headers, want 5", added) } gotTip, _, ok := store.HeaderTip() if !ok || gotTip != 10 { t.Fatalf("stored tip = %d, want 10", gotTip) } if calls != 1 { t.Fatalf("source asked %d times, want one window", calls) } } // TestAHeaderFromTheSourceThatDoesNotConnectIsRefused: the source is not trusted, it is // checked. A header whose parent is not the stored tip cannot be appended, and the error is // the same proof failure a peer would produce. func TestAHeaderFromTheSourceThatDoesNotConnectIsRefused(t *testing.T) { profile := chain.Regtest store := NewMemory() seedHeaders(t, &profile, store, 3, 600) // Mined on a parent the store does not have, so the chain does not connect. stranger := mineAt(t, chainhash.Hash{0: 0xee}, profile.GenesisHeader.Timestamp+3600, profile.PowLimitBits, 0x7f) client := testClient(t, &profile, store) client.cfg.HeaderSource = func(context.Context, uint32, uint32) ([]btcwire.BlockHeader, error) { return []btcwire.BlockHeader{stranger}, nil } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if _, err := client.SyncHeaders(ctx); err == nil { t.Fatal("a header that does not connect to the stored chain was accepted") } if tip, _, ok := store.HeaderTip(); !ok || tip != 3 { t.Fatalf("the store moved to %d on a header it should have refused", tip) } } // TestAShortAnswerEndsTheWindow: a source answers with what it holds, and a short run is how // it says it holds nothing more. The client must not keep asking. func TestAShortAnswerEndsTheWindow(t *testing.T) { profile := chain.Regtest store := NewMemory() tip := seedHeaders(t, &profile, store, 2, 600) header := mineAt(t, tip, profile.GenesisHeader.Timestamp+1800, profile.PowLimitBits, 0x55) calls := 0 client := testClient(t, &profile, store) client.cfg.HeaderSource = func(context.Context, uint32, uint32) ([]btcwire.BlockHeader, error) { calls++ if calls > 1 { return nil, nil } return []btcwire.BlockHeader{header}, nil } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() added, err := client.SyncHeaders(ctx) if err != nil { t.Fatalf("sync: %v", err) } if added != 1 { t.Fatalf("added %d headers, want 1", added) } if calls != 1 { t.Fatalf("source asked %d times after a short answer", calls) } } // TestABlockComesFromTheSourceWithoutAPeer: the block service is asked first, and a client with // no reachable peer still gets the block from it. The verify of the bytes against the header // happens above this layer, so what is asserted here is only that the source answered. func TestABlockComesFromTheSourceWithoutAPeer(t *testing.T) { profile := chain.Regtest store := NewMemory() seedHeaders(t, &profile, store, 3, 600) header, ok := store.Header(2) if !ok { t.Fatal("no header at 2") } want := []byte{0xde, 0xad, 0xbe, 0xef} client := testClient(t, &profile, store) client.cfg.BlockSource = func(_ context.Context, hash chainhash.Hash) ([]byte, error) { if hash != header.BlockHash() { t.Fatalf("source asked for %s, want %s", hash.String(), header.BlockHash().String()) } return want, nil } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() raw, err := client.Block(ctx, 2) if err != nil { t.Fatalf("a block the source held was not returned: %v", err) } if len(raw) != len(want) || raw[0] != want[0] { t.Fatalf("block = %v", raw) } } // TestAMissFallsThroughToThePeer: a source that does not hold the block returns nothing, and // the client then tries the tunnel. This client's peer address is dead, so the fall-through is // visible as the dial failing rather than as a silent empty block. func TestAMissFallsThroughToThePeer(t *testing.T) { profile := chain.Regtest store := NewMemory() seedHeaders(t, &profile, store, 2, 600) client := testClient(t, &profile, store) client.cfg.BlockSource = func(context.Context, chainhash.Hash) ([]byte, error) { return nil, nil } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if _, err := client.Block(ctx, 1); err == nil { t.Fatal("a miss was reported as a block") } } // TestFilterHeadersAreAdoptedFromTheRelay: a store whose filter header chain is trusted up to a // height takes the next heights from the relay's filter batches, computes the commitment exactly // as a cfheaders message would, and stores the filters with it. The chain that results is the // same one the peer would have sent, which is the whole point: the tunnel does not have to send // it. func TestFilterHeadersAreAdoptedFromTheRelay(t *testing.T) { profile := chain.Regtest store := NewMemory() seedHeaders(t, &profile, store, 5, 600) // Three heights of filter headers already trusted, as a first peer sync would leave them. var ( hashes []chainhash.Hash cfheaders []chainhash.Hash prev chainhash.Hash ) for i := 0; i <= 2; i++ { hash := chainhash.DoubleHashH([]byte{byte(i)}) prev = btcwire.FilterHeader(hash, prev) hashes = append(hashes, hash) cfheaders = append(cfheaders, prev) } if err := store.PutFilterHeaders(0, hashes, cfheaders); err != nil { t.Fatal(err) } f3 := []byte{3, 3, 3} f4 := []byte{4, 4, 4} f5 := []byte{5, 5} client := testClient(t, &profile, store) client.cfg.FilterSource = func(_ context.Context, from, to uint32) ([]Filters, error) { if from != 3 { t.Fatalf("source asked from %d, want 3", from) } if to != 5 { t.Fatalf("source asked to %d, want the header tip 5", to) } return []Filters{{From: 3, Filters: [][]byte{f3, f4, f5}}}, nil } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() adopted, err := client.adoptFilterSource(ctx) if err != nil { t.Fatal(err) } if adopted != 3 { t.Fatalf("adopted %d heights, want 3", adopted) } tip, header, ok := store.FilterHeaderTip() if !ok || tip != 5 { t.Fatalf("filter header tip = %d, want 5", tip) } // The commitment must be the one the chain implies, not one the source chose. want := btcwire.FilterHeader(chainhash.DoubleHashH(f5), btcwire.FilterHeader(chainhash.DoubleHashH(f4), btcwire.FilterHeader(chainhash.DoubleHashH(f3), cfheaders[2]))) if header != want { t.Fatalf("filter header at the tip = %s, want %s", header.String(), want.String()) } if got, ok := store.FilterHash(4); !ok || got != chainhash.DoubleHashH(f4) { t.Fatalf("filter hash at 4 = %s", got.String()) } if _, ok := store.Filter(5); !ok { t.Fatal("the adopted filter was not stored") } } // TestNothingIsAdoptedPastTheHeaderTip: the relay cannot make a client commit a filter for a // block whose header it has not verified, so a filter header chain that already reaches the // header tip leaves the source unasked. func TestNothingIsAdoptedPastTheHeaderTip(t *testing.T) { profile := chain.Regtest store := NewMemory() seedHeaders(t, &profile, store, 3, 600) var ( hashes []chainhash.Hash cfheaders []chainhash.Hash prev chainhash.Hash ) for i := 0; i <= 3; i++ { hash := chainhash.DoubleHashH([]byte{byte(i)}) prev = btcwire.FilterHeader(hash, prev) hashes = append(hashes, hash) cfheaders = append(cfheaders, prev) } if err := store.PutFilterHeaders(0, hashes, cfheaders); err != nil { t.Fatal(err) } client := testClient(t, &profile, store) client.cfg.FilterSource = func(_ context.Context, from, to uint32) ([]Filters, error) { t.Fatalf("the source was asked for %d..%d past the header tip", from, to) return nil, nil } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if _, err := client.adoptFilterSource(ctx); err != nil { t.Fatal(err) } } // TestASourceOnAnotherBranchFallsThroughToThePeer: after a reorg the relay may hold the new // header at a height and may still hold the old one, and the client's job is to refuse a header // that does not connect and let the peer say what the branch is. This client's peer is // unreachable, so the fall-through is visible as the dialect failing rather than as a proof-of-work // error or a stored header. func TestASourceOnAnotherBranchFallsThroughToThePeer(t *testing.T) { profile := chain.Regtest store := NewMemory() seedHeaders(t, &profile, store, 3, 600) stranger := mineAt(t, chainhash.Hash{0: 0x99}, profile.GenesisHeader.Timestamp+9000, profile.PowLimitBits, 0x42) asked := 0 client := testClient(t, &profile, store) client.cfg.HeaderSource = func(context.Context, uint32, uint32) ([]btcwire.BlockHeader, error) { asked++ return []btcwire.BlockHeader{stranger}, nil } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if _, err := client.SyncHeaders(ctx); err == nil { t.Fatal("a source on another branch was reported as a finished sync with no reachable peer") } if asked == 0 { t.Fatal("the source was never asked") } if tip, _, ok := store.HeaderTip(); !ok || tip != 3 { t.Fatalf("the store moved to %d on a header that does not connect", tip) } }