header_source_test.go raw

   1  package neutrino
   2  
   3  import (
   4  	"context"
   5  	"testing"
   6  	"time"
   7  
   8  	"git.smesh.lol/nostrino/pkg/btcwire"
   9  	"git.smesh.lol/nostrino/pkg/chain"
  10  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  11  )
  12  
  13  // TestHeadersArriveFromTheSourceWithoutAPeer is the shape the relay header path has to have:
  14  // a store anchored at a checkpoint, a source that holds the next run of headers, and no peer
  15  // at all. The peer address in this client is a dead one, so the sync only succeeds if the
  16  // source carried it to the tip and the failed dial is treated as "nothing more to fetch".
  17  func TestHeadersArriveFromTheSourceWithoutAPeer(t *testing.T) {
  18  	profile := chain.Regtest
  19  	store := NewMemory()
  20  
  21  	tip := seedHeaders(t, &profile, store, 5, 600)
  22  
  23  	// The run the source holds: five headers mined on top of the stored tip.
  24  	run := make([]btcwire.BlockHeader, 0, 5)
  25  
  26  	prev := tip
  27  
  28  	for i := 1; i <= 5; i++ {
  29  		header := mineAt(t, prev, profile.GenesisHeader.Timestamp+600*uint32(5+i), profile.PowLimitBits, byte(0xa0+i))
  30  		run = append(run, header)
  31  
  32  		prev = header.BlockHash()
  33  	}
  34  
  35  	calls := 0
  36  
  37  	client := testClient(t, &profile, store)
  38  	client.cfg.HeaderSource = func(_ context.Context, from, to uint32) ([]btcwire.BlockHeader, error) {
  39  		calls++
  40  
  41  		if from != 6 {
  42  			t.Fatalf("source asked for %d..%d, want the run from 6", from, to)
  43  		}
  44  
  45  		return run, nil
  46  	}
  47  
  48  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  49  	defer cancel()
  50  
  51  	added, err := client.SyncHeaders(ctx)
  52  
  53  	if err != nil {
  54  		t.Fatalf("a source that carried the chain to its tip was reported as a failure: %v", err)
  55  	}
  56  
  57  	if added != 5 {
  58  		t.Fatalf("added %d headers, want 5", added)
  59  	}
  60  
  61  	gotTip, _, ok := store.HeaderTip()
  62  
  63  	if !ok || gotTip != 10 {
  64  		t.Fatalf("stored tip = %d, want 10", gotTip)
  65  	}
  66  
  67  	if calls != 1 {
  68  		t.Fatalf("source asked %d times, want one window", calls)
  69  	}
  70  }
  71  
  72  // TestAHeaderFromTheSourceThatDoesNotConnectIsRefused: the source is not trusted, it is
  73  // checked. A header whose parent is not the stored tip cannot be appended, and the error is
  74  // the same proof failure a peer would produce.
  75  func TestAHeaderFromTheSourceThatDoesNotConnectIsRefused(t *testing.T) {
  76  	profile := chain.Regtest
  77  	store := NewMemory()
  78  
  79  	seedHeaders(t, &profile, store, 3, 600)
  80  
  81  	// Mined on a parent the store does not have, so the chain does not connect.
  82  	stranger := mineAt(t, chainhash.Hash{0: 0xee}, profile.GenesisHeader.Timestamp+3600,
  83  		profile.PowLimitBits, 0x7f)
  84  
  85  	client := testClient(t, &profile, store)
  86  	client.cfg.HeaderSource = func(context.Context, uint32, uint32) ([]btcwire.BlockHeader, error) {
  87  		return []btcwire.BlockHeader{stranger}, nil
  88  	}
  89  
  90  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  91  	defer cancel()
  92  
  93  	if _, err := client.SyncHeaders(ctx); err == nil {
  94  		t.Fatal("a header that does not connect to the stored chain was accepted")
  95  	}
  96  
  97  	if tip, _, ok := store.HeaderTip(); !ok || tip != 3 {
  98  		t.Fatalf("the store moved to %d on a header it should have refused", tip)
  99  	}
 100  }
 101  
 102  // TestAShortAnswerEndsTheWindow: a source answers with what it holds, and a short run is how
 103  // it says it holds nothing more. The client must not keep asking.
 104  func TestAShortAnswerEndsTheWindow(t *testing.T) {
 105  	profile := chain.Regtest
 106  	store := NewMemory()
 107  
 108  	tip := seedHeaders(t, &profile, store, 2, 600)
 109  
 110  	header := mineAt(t, tip, profile.GenesisHeader.Timestamp+1800, profile.PowLimitBits, 0x55)
 111  
 112  	calls := 0
 113  
 114  	client := testClient(t, &profile, store)
 115  	client.cfg.HeaderSource = func(context.Context, uint32, uint32) ([]btcwire.BlockHeader, error) {
 116  		calls++
 117  
 118  		if calls > 1 {
 119  			return nil, nil
 120  		}
 121  
 122  		return []btcwire.BlockHeader{header}, nil
 123  	}
 124  
 125  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 126  	defer cancel()
 127  
 128  	added, err := client.SyncHeaders(ctx)
 129  
 130  	if err != nil {
 131  		t.Fatalf("sync: %v", err)
 132  	}
 133  
 134  	if added != 1 {
 135  		t.Fatalf("added %d headers, want 1", added)
 136  	}
 137  
 138  	if calls != 1 {
 139  		t.Fatalf("source asked %d times after a short answer", calls)
 140  	}
 141  }
 142  
 143  // TestABlockComesFromTheSourceWithoutAPeer: the block service is asked first, and a client with
 144  // no reachable peer still gets the block from it. The verify of the bytes against the header
 145  // happens above this layer, so what is asserted here is only that the source answered.
 146  func TestABlockComesFromTheSourceWithoutAPeer(t *testing.T) {
 147  	profile := chain.Regtest
 148  	store := NewMemory()
 149  
 150  	seedHeaders(t, &profile, store, 3, 600)
 151  
 152  	header, ok := store.Header(2)
 153  
 154  	if !ok {
 155  		t.Fatal("no header at 2")
 156  	}
 157  
 158  	want := []byte{0xde, 0xad, 0xbe, 0xef}
 159  
 160  	client := testClient(t, &profile, store)
 161  	client.cfg.BlockSource = func(_ context.Context, hash chainhash.Hash) ([]byte, error) {
 162  		if hash != header.BlockHash() {
 163  			t.Fatalf("source asked for %s, want %s", hash.String(), header.BlockHash().String())
 164  		}
 165  
 166  		return want, nil
 167  	}
 168  
 169  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 170  	defer cancel()
 171  
 172  	raw, err := client.Block(ctx, 2)
 173  
 174  	if err != nil {
 175  		t.Fatalf("a block the source held was not returned: %v", err)
 176  	}
 177  
 178  	if len(raw) != len(want) || raw[0] != want[0] {
 179  		t.Fatalf("block = %v", raw)
 180  	}
 181  }
 182  
 183  // TestAMissFallsThroughToThePeer: a source that does not hold the block returns nothing, and
 184  // the client then tries the tunnel. This client's peer address is dead, so the fall-through is
 185  // visible as the dial failing rather than as a silent empty block.
 186  func TestAMissFallsThroughToThePeer(t *testing.T) {
 187  	profile := chain.Regtest
 188  	store := NewMemory()
 189  
 190  	seedHeaders(t, &profile, store, 2, 600)
 191  
 192  	client := testClient(t, &profile, store)
 193  	client.cfg.BlockSource = func(context.Context, chainhash.Hash) ([]byte, error) {
 194  		return nil, nil
 195  	}
 196  
 197  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
 198  	defer cancel()
 199  
 200  	if _, err := client.Block(ctx, 1); err == nil {
 201  		t.Fatal("a miss was reported as a block")
 202  	}
 203  }
 204  
 205  // TestFilterHeadersAreAdoptedFromTheRelay: a store whose filter header chain is trusted up to a
 206  // height takes the next heights from the relay's filter batches, computes the commitment exactly
 207  // as a cfheaders message would, and stores the filters with it. The chain that results is the
 208  // same one the peer would have sent, which is the whole point: the tunnel does not have to send
 209  // it.
 210  func TestFilterHeadersAreAdoptedFromTheRelay(t *testing.T) {
 211  	profile := chain.Regtest
 212  	store := NewMemory()
 213  
 214  	seedHeaders(t, &profile, store, 5, 600)
 215  
 216  	// Three heights of filter headers already trusted, as a first peer sync would leave them.
 217  	var (
 218  		hashes    []chainhash.Hash
 219  		cfheaders []chainhash.Hash
 220  		prev      chainhash.Hash
 221  	)
 222  
 223  	for i := 0; i <= 2; i++ {
 224  		hash := chainhash.DoubleHashH([]byte{byte(i)})
 225  		prev = btcwire.FilterHeader(hash, prev)
 226  		hashes = append(hashes, hash)
 227  		cfheaders = append(cfheaders, prev)
 228  	}
 229  
 230  	if err := store.PutFilterHeaders(0, hashes, cfheaders); err != nil {
 231  		t.Fatal(err)
 232  	}
 233  
 234  	f3 := []byte{3, 3, 3}
 235  	f4 := []byte{4, 4, 4}
 236  	f5 := []byte{5, 5}
 237  
 238  	client := testClient(t, &profile, store)
 239  	client.cfg.FilterSource = func(_ context.Context, from, to uint32) ([]Filters, error) {
 240  		if from != 3 {
 241  			t.Fatalf("source asked from %d, want 3", from)
 242  		}
 243  
 244  		if to != 5 {
 245  			t.Fatalf("source asked to %d, want the header tip 5", to)
 246  		}
 247  
 248  		return []Filters{{From: 3, Filters: [][]byte{f3, f4, f5}}}, nil
 249  	}
 250  
 251  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 252  	defer cancel()
 253  
 254  	adopted, err := client.adoptFilterSource(ctx)
 255  
 256  	if err != nil {
 257  		t.Fatal(err)
 258  	}
 259  
 260  	if adopted != 3 {
 261  		t.Fatalf("adopted %d heights, want 3", adopted)
 262  	}
 263  
 264  	tip, header, ok := store.FilterHeaderTip()
 265  
 266  	if !ok || tip != 5 {
 267  		t.Fatalf("filter header tip = %d, want 5", tip)
 268  	}
 269  
 270  	// The commitment must be the one the chain implies, not one the source chose.
 271  	want := btcwire.FilterHeader(chainhash.DoubleHashH(f5),
 272  		btcwire.FilterHeader(chainhash.DoubleHashH(f4),
 273  			btcwire.FilterHeader(chainhash.DoubleHashH(f3), cfheaders[2])))
 274  
 275  	if header != want {
 276  		t.Fatalf("filter header at the tip = %s, want %s", header.String(), want.String())
 277  	}
 278  
 279  	if got, ok := store.FilterHash(4); !ok || got != chainhash.DoubleHashH(f4) {
 280  		t.Fatalf("filter hash at 4 = %s", got.String())
 281  	}
 282  
 283  	if _, ok := store.Filter(5); !ok {
 284  		t.Fatal("the adopted filter was not stored")
 285  	}
 286  }
 287  
 288  // TestNothingIsAdoptedPastTheHeaderTip: the relay cannot make a client commit a filter for a
 289  // block whose header it has not verified, so a filter header chain that already reaches the
 290  // header tip leaves the source unasked.
 291  func TestNothingIsAdoptedPastTheHeaderTip(t *testing.T) {
 292  	profile := chain.Regtest
 293  	store := NewMemory()
 294  
 295  	seedHeaders(t, &profile, store, 3, 600)
 296  
 297  	var (
 298  		hashes    []chainhash.Hash
 299  		cfheaders []chainhash.Hash
 300  		prev      chainhash.Hash
 301  	)
 302  
 303  	for i := 0; i <= 3; i++ {
 304  		hash := chainhash.DoubleHashH([]byte{byte(i)})
 305  		prev = btcwire.FilterHeader(hash, prev)
 306  		hashes = append(hashes, hash)
 307  		cfheaders = append(cfheaders, prev)
 308  	}
 309  
 310  	if err := store.PutFilterHeaders(0, hashes, cfheaders); err != nil {
 311  		t.Fatal(err)
 312  	}
 313  
 314  	client := testClient(t, &profile, store)
 315  	client.cfg.FilterSource = func(_ context.Context, from, to uint32) ([]Filters, error) {
 316  		t.Fatalf("the source was asked for %d..%d past the header tip", from, to)
 317  
 318  		return nil, nil
 319  	}
 320  
 321  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
 322  	defer cancel()
 323  
 324  	if _, err := client.adoptFilterSource(ctx); err != nil {
 325  		t.Fatal(err)
 326  	}
 327  }
 328  
 329  // TestASourceOnAnotherBranchFallsThroughToThePeer: after a reorg the relay may hold the new
 330  // header at a height and may still hold the old one, and the client's job is to refuse a header
 331  // that does not connect and let the peer say what the branch is. This client's peer is
 332  // unreachable, so the fall-through is visible as the dialect failing rather than as a proof-of-work
 333  // error or a stored header.
 334  func TestASourceOnAnotherBranchFallsThroughToThePeer(t *testing.T) {
 335  	profile := chain.Regtest
 336  	store := NewMemory()
 337  
 338  	seedHeaders(t, &profile, store, 3, 600)
 339  
 340  	stranger := mineAt(t, chainhash.Hash{0: 0x99}, profile.GenesisHeader.Timestamp+9000,
 341  		profile.PowLimitBits, 0x42)
 342  
 343  	asked := 0
 344  
 345  	client := testClient(t, &profile, store)
 346  	client.cfg.HeaderSource = func(context.Context, uint32, uint32) ([]btcwire.BlockHeader, error) {
 347  		asked++
 348  
 349  		return []btcwire.BlockHeader{stranger}, nil
 350  	}
 351  
 352  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
 353  	defer cancel()
 354  
 355  	if _, err := client.SyncHeaders(ctx); err == nil {
 356  		t.Fatal("a source on another branch was reported as a finished sync with no reachable peer")
 357  	}
 358  
 359  	if asked == 0 {
 360  		t.Fatal("the source was never asked")
 361  	}
 362  
 363  	if tip, _, ok := store.HeaderTip(); !ok || tip != 3 {
 364  		t.Fatalf("the store moved to %d on a header that does not connect", tip)
 365  	}
 366  }
 367