backup_test.go raw

   1  package backup
   2  
   3  import (
   4  	"bytes"
   5  	"crypto/sha256"
   6  	"encoding/binary"
   7  	"encoding/hex"
   8  	"strings"
   9  	"testing"
  10  
  11  	"git.smesh.lol/nostrino/pkg/btcwire"
  12  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  13  	"time"
  14  )
  15  
  16  // header builds a run of distinguishable headers.
  17  func headerRun(from, count uint32) []byte {
  18  	out := make([]byte, 0, int(count)*HeaderSize)
  19  
  20  	for i := uint32(0); i < count; i++ {
  21  		header := make([]byte, HeaderSize)
  22  		binary.LittleEndian.PutUint32(header, from+i)
  23  		out = append(out, header...)
  24  	}
  25  
  26  	return out
  27  }
  28  
  29  // filterHeaderRun builds a run of filter hash and filter header pairs.
  30  func filterHeaderRun(from, count uint32) []byte {
  31  	out := make([]byte, 0, int(count)*FilterHeaderSize)
  32  
  33  	for i := uint32(0); i < count; i++ {
  34  		pair := make([]byte, FilterHeaderSize)
  35  		binary.LittleEndian.PutUint32(pair, from+i)
  36  		binary.LittleEndian.PutUint32(pair[32:], from+i+1_000_000)
  37  		out = append(out, pair...)
  38  	}
  39  
  40  	return out
  41  }
  42  
  43  // filterRun builds filters of alternating size, so a chunk is not a fixed stride.
  44  func filterRun(from, count uint32) ([]byte, []FilterRecord) {
  45  	var payload []byte
  46  
  47  	records := make([]FilterRecord, 0, count)
  48  
  49  	for i := uint32(0); i < count; i++ {
  50  		record := FilterRecord{Height: from + i, Filter: make([]byte, 20+int(i%7))}
  51  
  52  		for j := range record.Filter {
  53  			record.Filter[j] = byte(i)
  54  		}
  55  
  56  		record.BlockHash[0] = byte(i)
  57  		record.FilterHash[0] = byte(i + 1)
  58  
  59  		records = append(records, record)
  60  	}
  61  
  62  	payload, err := AppendFilters(payload, records)
  63  
  64  	if err != nil {
  65  		panic(err)
  66  	}
  67  
  68  	return payload, records
  69  }
  70  
  71  func TestChunksRoundTrip(t *testing.T) {
  72  	filters, records := filterRun(11, 5)
  73  
  74  	chunks := []Chunk{
  75  		{Kind: Headers, From: 11, Count: 5, Payload: headerRun(11, 5)},
  76  		{Kind: FilterHeaders, From: 11, Count: 5, Payload: filterHeaderRun(11, 5)},
  77  		{Kind: Filters, From: 11, Count: 5, Payload: filters},
  78  	}
  79  
  80  	for _, chunk := range chunks {
  81  		raw, err := Encode(chunk)
  82  
  83  		if err != nil {
  84  			t.Fatalf("%s: %v", chunk.Kind, err)
  85  		}
  86  
  87  		decoded, err := Decode(raw)
  88  
  89  		if err != nil {
  90  			t.Fatalf("%s: %v", chunk.Kind, err)
  91  		}
  92  
  93  		if decoded.Kind != chunk.Kind || decoded.From != chunk.From || decoded.Count != chunk.Count {
  94  			t.Fatalf("%s round trip: %+v", chunk.Kind, decoded)
  95  		}
  96  
  97  		if !bytes.Equal(decoded.Payload, chunk.Payload) {
  98  			t.Fatalf("%s: the payload changed", chunk.Kind)
  99  		}
 100  	}
 101  
 102  	decodedFilters, err := Decode(mustEncode(t, chunks[2]))
 103  
 104  	if err != nil {
 105  		t.Fatal(err)
 106  	}
 107  
 108  	read, err := ReadFilters(decodedFilters.Payload)
 109  
 110  	if err != nil {
 111  		t.Fatal(err)
 112  	}
 113  
 114  	if len(read) != len(records) {
 115  		t.Fatalf("%d filters, want %d", len(read), len(records))
 116  	}
 117  
 118  	for i := range records {
 119  		if read[i].Height != records[i].Height ||
 120  			read[i].BlockHash != records[i].BlockHash ||
 121  			read[i].FilterHash != records[i].FilterHash ||
 122  			!bytes.Equal(read[i].Filter, records[i].Filter) {
 123  			t.Fatalf("filter %d round trip: %+v", i, read[i])
 124  		}
 125  	}
 126  }
 127  
 128  func mustEncode(t *testing.T, chunk Chunk) []byte {
 129  	t.Helper()
 130  
 131  	raw, err := Encode(chunk)
 132  
 133  	if err != nil {
 134  		t.Fatal(err)
 135  	}
 136  
 137  	return raw
 138  }
 139  
 140  func TestAChunkRefusesACountItCannotKeep(t *testing.T) {
 141  	chunk := Chunk{Kind: Headers, From: 1, Count: 3, Payload: headerRun(1, 2)}
 142  
 143  	if _, err := Encode(chunk); err != nil {
 144  		t.Fatalf("Encode: %v", err)
 145  	}
 146  
 147  	raw := mustEncode(t, chunk)
 148  	raw[10] = 4 // the count field
 149  
 150  	if _, err := Decode(raw); err == nil {
 151  		t.Fatal("a chunk with the wrong header count was accepted")
 152  	}
 153  }
 154  
 155  func TestAChunkRefusesAShortFilter(t *testing.T) {
 156  	payload, _ := filterRun(1, 1)
 157  	payload = payload[:len(payload)-1]
 158  
 159  	chunk := Chunk{Kind: Filters, From: 1, Count: 1, Payload: payload}
 160  
 161  	if _, err := Encode(chunk); err != nil {
 162  		t.Fatalf("Encode: %v", err)
 163  	}
 164  
 165  	if _, err := Decode(mustEncode(t, chunk)); err == nil {
 166  		t.Fatal("a filter that runs past its chunk was accepted")
 167  	}
 168  }
 169  
 170  func TestDecodeRefusesAnotherFormat(t *testing.T) {
 171  	cases := map[string][]byte{
 172  		"short":       {1, 2, 3},
 173  		"bad magic":   append([]byte("XBTC"), make([]byte, 32)...),
 174  		"bad version": append(append(Magic[:], 9, 1), make([]byte, 12)...),
 175  		"bad kind":    append(append(Magic[:], Version, 9), make([]byte, 12)...),
 176  	}
 177  
 178  	for name, raw := range cases {
 179  		if _, err := Decode(raw); err == nil {
 180  			t.Fatalf("%s: accepted", name)
 181  		}
 182  	}
 183  }
 184  
 185  // manifestFixture builds a valid manifest from real chunks: heights 11..20, two header chunks
 186  // and one filter chunk.
 187  func manifestFixture(t *testing.T) (Manifest, map[string][]byte) {
 188  	t.Helper()
 189  
 190  	files := map[string][]byte{}
 191  	chunks := []ChunkInfo{}
 192  
 193  	add := func(chunk Chunk) {
 194  		raw := mustEncode(t, chunk)
 195  		info := ChunkInfo{
 196  			File:   ChunkFile(chunk.Kind, chunk.From),
 197  			Kind:   chunk.Kind,
 198  			From:   chunk.From,
 199  			Count:  chunk.Count,
 200  			Bytes:  uint64(len(raw)),
 201  			SHA256: Sum(raw),
 202  		}
 203  		files[info.File] = raw
 204  		chunks = append(chunks, info)
 205  	}
 206  
 207  	add(Chunk{Kind: Headers, From: 11, Count: 5, Payload: headerRun(11, 5)})
 208  	add(Chunk{Kind: Headers, From: 16, Count: 5, Payload: headerRun(16, 5)})
 209  	add(Chunk{Kind: FilterHeaders, From: 11, Count: 10, Payload: filterHeaderRun(11, 10)})
 210  
 211  	payload, _ := filterRun(11, 10)
 212  	add(Chunk{Kind: Filters, From: 11, Count: 10, Payload: payload})
 213  
 214  	filterBytes := uint64(0)
 215  
 216  	for _, chunk := range chunks {
 217  		if chunk.Kind == Filters {
 218  			filterBytes += chunk.Bytes
 219  		}
 220  	}
 221  
 222  	manifest := Manifest{
 223  		Version: Version,
 224  		Created: time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC),
 225  		Chains: []Chain{{
 226  			Name: "btc", Network: "regtest",
 227  			Anchor: Anchor{
 228  				Height:       10,
 229  				BlockHash:    strings.Repeat("ab", 32),
 230  				FilterHeader: strings.Repeat("cd", 32),
 231  			},
 232  			HeaderFrom:    11,
 233  			FilterFrom:    11,
 234  			Tip:           20,
 235  			Headers:       10,
 236  			FilterHeaders: 10,
 237  			Filters:       10,
 238  			FilterBytes:   filterBytes,
 239  			Chunks:        chunks,
 240  		}},
 241  	}
 242  
 243  	return manifest, files
 244  }
 245  
 246  func TestAManifestRoundTrips(t *testing.T) {
 247  	manifest, files := manifestFixture(t)
 248  
 249  	raw, err := Marshal(manifest)
 250  
 251  	if err != nil {
 252  		t.Fatalf("Marshal: %v", err)
 253  	}
 254  
 255  	parsed, err := Parse(raw)
 256  
 257  	if err != nil {
 258  		t.Fatalf("Parse: %v", err)
 259  	}
 260  
 261  	if len(parsed.Chains) != 1 || parsed.Chains[0].Tip != 20 {
 262  		t.Fatalf("parsed %+v", parsed)
 263  	}
 264  
 265  	if got := parsed.ChunkFiles(); len(got) != len(files) {
 266  		t.Fatalf("the manifest names %d files, it has %d", len(got), len(files))
 267  	}
 268  
 269  	for _, chain := range parsed.Chains {
 270  		for _, info := range chain.Chunks {
 271  			if _, err := VerifyChunk(info, files[info.File]); err != nil {
 272  				t.Fatalf("%s: %v", info.File, err)
 273  			}
 274  		}
 275  	}
 276  }
 277  
 278  func TestAManifestRefusesAHole(t *testing.T) {
 279  	manifest, _ := manifestFixture(t)
 280  	manifest.Chains[0].Chunks = manifest.Chains[0].Chunks[1:]
 281  
 282  	if _, err := Marshal(manifest); err == nil {
 283  		t.Fatal("a manifest that begins above the anchor was accepted")
 284  	}
 285  
 286  	manifest, _ = manifestFixture(t)
 287  	manifest.Chains[0].Chunks[0].From = 12
 288  	manifest.Chains[0].Chunks[0].File = ChunkFile(Headers, 12)
 289  
 290  	if _, err := Marshal(manifest); err == nil {
 291  		t.Fatal("a manifest with a gap was accepted")
 292  	}
 293  }
 294  
 295  func TestAManifestRefusesAShortCover(t *testing.T) {
 296  	manifest, _ := manifestFixture(t)
 297  	manifest.Chains[0].Tip = 19
 298  
 299  	if _, err := Marshal(manifest); err == nil {
 300  		t.Fatal("a manifest that stops below its own counts was accepted")
 301  	}
 302  }
 303  
 304  func TestAManifestRefusesAFileFromElsewhere(t *testing.T) {
 305  	manifest, files := manifestFixture(t)
 306  
 307  	info := manifest.Chains[0].Chunks[0]
 308  	info.SHA256 = strings.Repeat("00", 32)
 309  
 310  	if _, err := VerifyChunk(info, files[info.File]); err == nil {
 311  		t.Fatal("a chunk whose digest does not match was accepted")
 312  	}
 313  
 314  	info = manifest.Chains[0].Chunks[0]
 315  	info.From++
 316  
 317  	if _, err := VerifyChunk(info, files[info.File]); err == nil {
 318  		t.Fatal("a chunk from another height was accepted")
 319  	}
 320  }
 321  
 322  func TestAManifestRefusesAnAnchorThatIsNotAHash(t *testing.T) {
 323  	manifest, _ := manifestFixture(t)
 324  	manifest.Chains[0].Anchor.BlockHash = "nothex"
 325  
 326  	if _, err := Marshal(manifest); err == nil {
 327  		t.Fatal("a manifest with a bad anchor was accepted")
 328  	}
 329  }
 330  
 331  func TestSumIsOverTheWholeFile(t *testing.T) {
 332  	raw := mustEncode(t, Chunk{Kind: Headers, From: 1, Count: 1, Payload: headerRun(1, 1)})
 333  	want := sha256.Sum256(raw)
 334  
 335  	if Sum(raw) != hex.EncodeToString(want[:]) {
 336  		t.Fatal("Sum is not the file's SHA-256")
 337  	}
 338  }
 339  
 340  // memStore is a store with a fixed answer, for the export tests.
 341  type memStore struct {
 342  	headers map[uint32]btcwire.BlockHeader
 343  	hashes  map[uint32]chainhash.Hash
 344  	filters map[uint32][]byte
 345  }
 346  
 347  func (m memStore) Header(height uint32) (btcwire.BlockHeader, bool) {
 348  	header, ok := m.headers[height]
 349  
 350  	return header, ok
 351  }
 352  
 353  func (m memStore) FilterHeader(height uint32) (chainhash.Hash, bool) {
 354  	hash, ok := m.hashes[height]
 355  
 356  	return hash, ok
 357  }
 358  
 359  func (m memStore) FilterHash(height uint32) (chainhash.Hash, bool) {
 360  	hash, ok := m.hashes[height]
 361  
 362  	return hash, ok
 363  }
 364  
 365  func (m memStore) Filter(height uint32) ([]byte, bool) {
 366  	filter, ok := m.filters[height]
 367  
 368  	return filter, ok
 369  }
 370  
 371  // TestExportFiltersUnboundedCount: a zero count means "as many as the byte budget allows", which
 372  // is what the channel asks for; treating it as zero records exported no filters at all.
 373  func TestExportFiltersUnboundedCount(t *testing.T) {
 374  	store := memStore{
 375  		headers: map[uint32]btcwire.BlockHeader{},
 376  		hashes:  map[uint32]chainhash.Hash{},
 377  		filters: map[uint32][]byte{},
 378  	}
 379  
 380  	for height := uint32(1); height <= 3; height++ {
 381  		var header btcwire.BlockHeader
 382  
 383  		header.Version = int32(height)
 384  		store.headers[height] = header
 385  		store.filters[height] = []byte{byte(height)}
 386  		store.hashes[height] = chainhash.Hash{byte(height)}
 387  	}
 388  
 389  	chunk, err := ExportFilters(store, 1, 0, 1<<20)
 390  
 391  	if err != nil {
 392  		t.Fatalf("ExportFilters: %v", err)
 393  	}
 394  
 395  	if chunk.Count != 3 || len(chunk.Payload) == 0 {
 396  		t.Fatalf("exported %d filters", chunk.Count)
 397  	}
 398  
 399  	// The byte budget still bounds it.
 400  	small, err := ExportFilters(store, 1, 0, 60)
 401  
 402  	if err != nil {
 403  		t.Fatalf("ExportFilters: %v", err)
 404  	}
 405  
 406  	if small.Count == 0 || small.Count >= 3 {
 407  		t.Fatalf("a 60-byte budget exported %d filters", small.Count)
 408  	}
 409  }
 410