package backup import ( "bytes" "crypto/sha256" "encoding/binary" "encoding/hex" "strings" "testing" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "time" ) // header builds a run of distinguishable headers. func headerRun(from, count uint32) []byte { out := make([]byte, 0, int(count)*HeaderSize) for i := uint32(0); i < count; i++ { header := make([]byte, HeaderSize) binary.LittleEndian.PutUint32(header, from+i) out = append(out, header...) } return out } // filterHeaderRun builds a run of filter hash and filter header pairs. func filterHeaderRun(from, count uint32) []byte { out := make([]byte, 0, int(count)*FilterHeaderSize) for i := uint32(0); i < count; i++ { pair := make([]byte, FilterHeaderSize) binary.LittleEndian.PutUint32(pair, from+i) binary.LittleEndian.PutUint32(pair[32:], from+i+1_000_000) out = append(out, pair...) } return out } // filterRun builds filters of alternating size, so a chunk is not a fixed stride. func filterRun(from, count uint32) ([]byte, []FilterRecord) { var payload []byte records := make([]FilterRecord, 0, count) for i := uint32(0); i < count; i++ { record := FilterRecord{Height: from + i, Filter: make([]byte, 20+int(i%7))} for j := range record.Filter { record.Filter[j] = byte(i) } record.BlockHash[0] = byte(i) record.FilterHash[0] = byte(i + 1) records = append(records, record) } payload, err := AppendFilters(payload, records) if err != nil { panic(err) } return payload, records } func TestChunksRoundTrip(t *testing.T) { filters, records := filterRun(11, 5) chunks := []Chunk{ {Kind: Headers, From: 11, Count: 5, Payload: headerRun(11, 5)}, {Kind: FilterHeaders, From: 11, Count: 5, Payload: filterHeaderRun(11, 5)}, {Kind: Filters, From: 11, Count: 5, Payload: filters}, } for _, chunk := range chunks { raw, err := Encode(chunk) if err != nil { t.Fatalf("%s: %v", chunk.Kind, err) } decoded, err := Decode(raw) if err != nil { t.Fatalf("%s: %v", chunk.Kind, err) } if decoded.Kind != chunk.Kind || decoded.From != chunk.From || decoded.Count != chunk.Count { t.Fatalf("%s round trip: %+v", chunk.Kind, decoded) } if !bytes.Equal(decoded.Payload, chunk.Payload) { t.Fatalf("%s: the payload changed", chunk.Kind) } } decodedFilters, err := Decode(mustEncode(t, chunks[2])) if err != nil { t.Fatal(err) } read, err := ReadFilters(decodedFilters.Payload) if err != nil { t.Fatal(err) } if len(read) != len(records) { t.Fatalf("%d filters, want %d", len(read), len(records)) } for i := range records { if read[i].Height != records[i].Height || read[i].BlockHash != records[i].BlockHash || read[i].FilterHash != records[i].FilterHash || !bytes.Equal(read[i].Filter, records[i].Filter) { t.Fatalf("filter %d round trip: %+v", i, read[i]) } } } func mustEncode(t *testing.T, chunk Chunk) []byte { t.Helper() raw, err := Encode(chunk) if err != nil { t.Fatal(err) } return raw } func TestAChunkRefusesACountItCannotKeep(t *testing.T) { chunk := Chunk{Kind: Headers, From: 1, Count: 3, Payload: headerRun(1, 2)} if _, err := Encode(chunk); err != nil { t.Fatalf("Encode: %v", err) } raw := mustEncode(t, chunk) raw[10] = 4 // the count field if _, err := Decode(raw); err == nil { t.Fatal("a chunk with the wrong header count was accepted") } } func TestAChunkRefusesAShortFilter(t *testing.T) { payload, _ := filterRun(1, 1) payload = payload[:len(payload)-1] chunk := Chunk{Kind: Filters, From: 1, Count: 1, Payload: payload} if _, err := Encode(chunk); err != nil { t.Fatalf("Encode: %v", err) } if _, err := Decode(mustEncode(t, chunk)); err == nil { t.Fatal("a filter that runs past its chunk was accepted") } } func TestDecodeRefusesAnotherFormat(t *testing.T) { cases := map[string][]byte{ "short": {1, 2, 3}, "bad magic": append([]byte("XBTC"), make([]byte, 32)...), "bad version": append(append(Magic[:], 9, 1), make([]byte, 12)...), "bad kind": append(append(Magic[:], Version, 9), make([]byte, 12)...), } for name, raw := range cases { if _, err := Decode(raw); err == nil { t.Fatalf("%s: accepted", name) } } } // manifestFixture builds a valid manifest from real chunks: heights 11..20, two header chunks // and one filter chunk. func manifestFixture(t *testing.T) (Manifest, map[string][]byte) { t.Helper() files := map[string][]byte{} chunks := []ChunkInfo{} add := func(chunk Chunk) { raw := mustEncode(t, chunk) info := ChunkInfo{ File: ChunkFile(chunk.Kind, chunk.From), Kind: chunk.Kind, From: chunk.From, Count: chunk.Count, Bytes: uint64(len(raw)), SHA256: Sum(raw), } files[info.File] = raw chunks = append(chunks, info) } add(Chunk{Kind: Headers, From: 11, Count: 5, Payload: headerRun(11, 5)}) add(Chunk{Kind: Headers, From: 16, Count: 5, Payload: headerRun(16, 5)}) add(Chunk{Kind: FilterHeaders, From: 11, Count: 10, Payload: filterHeaderRun(11, 10)}) payload, _ := filterRun(11, 10) add(Chunk{Kind: Filters, From: 11, Count: 10, Payload: payload}) filterBytes := uint64(0) for _, chunk := range chunks { if chunk.Kind == Filters { filterBytes += chunk.Bytes } } manifest := Manifest{ Version: Version, Created: time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC), Chains: []Chain{{ Name: "btc", Network: "regtest", Anchor: Anchor{ Height: 10, BlockHash: strings.Repeat("ab", 32), FilterHeader: strings.Repeat("cd", 32), }, HeaderFrom: 11, FilterFrom: 11, Tip: 20, Headers: 10, FilterHeaders: 10, Filters: 10, FilterBytes: filterBytes, Chunks: chunks, }}, } return manifest, files } func TestAManifestRoundTrips(t *testing.T) { manifest, files := manifestFixture(t) raw, err := Marshal(manifest) if err != nil { t.Fatalf("Marshal: %v", err) } parsed, err := Parse(raw) if err != nil { t.Fatalf("Parse: %v", err) } if len(parsed.Chains) != 1 || parsed.Chains[0].Tip != 20 { t.Fatalf("parsed %+v", parsed) } if got := parsed.ChunkFiles(); len(got) != len(files) { t.Fatalf("the manifest names %d files, it has %d", len(got), len(files)) } for _, chain := range parsed.Chains { for _, info := range chain.Chunks { if _, err := VerifyChunk(info, files[info.File]); err != nil { t.Fatalf("%s: %v", info.File, err) } } } } func TestAManifestRefusesAHole(t *testing.T) { manifest, _ := manifestFixture(t) manifest.Chains[0].Chunks = manifest.Chains[0].Chunks[1:] if _, err := Marshal(manifest); err == nil { t.Fatal("a manifest that begins above the anchor was accepted") } manifest, _ = manifestFixture(t) manifest.Chains[0].Chunks[0].From = 12 manifest.Chains[0].Chunks[0].File = ChunkFile(Headers, 12) if _, err := Marshal(manifest); err == nil { t.Fatal("a manifest with a gap was accepted") } } func TestAManifestRefusesAShortCover(t *testing.T) { manifest, _ := manifestFixture(t) manifest.Chains[0].Tip = 19 if _, err := Marshal(manifest); err == nil { t.Fatal("a manifest that stops below its own counts was accepted") } } func TestAManifestRefusesAFileFromElsewhere(t *testing.T) { manifest, files := manifestFixture(t) info := manifest.Chains[0].Chunks[0] info.SHA256 = strings.Repeat("00", 32) if _, err := VerifyChunk(info, files[info.File]); err == nil { t.Fatal("a chunk whose digest does not match was accepted") } info = manifest.Chains[0].Chunks[0] info.From++ if _, err := VerifyChunk(info, files[info.File]); err == nil { t.Fatal("a chunk from another height was accepted") } } func TestAManifestRefusesAnAnchorThatIsNotAHash(t *testing.T) { manifest, _ := manifestFixture(t) manifest.Chains[0].Anchor.BlockHash = "nothex" if _, err := Marshal(manifest); err == nil { t.Fatal("a manifest with a bad anchor was accepted") } } func TestSumIsOverTheWholeFile(t *testing.T) { raw := mustEncode(t, Chunk{Kind: Headers, From: 1, Count: 1, Payload: headerRun(1, 1)}) want := sha256.Sum256(raw) if Sum(raw) != hex.EncodeToString(want[:]) { t.Fatal("Sum is not the file's SHA-256") } } // memStore is a store with a fixed answer, for the export tests. type memStore struct { headers map[uint32]btcwire.BlockHeader hashes map[uint32]chainhash.Hash filters map[uint32][]byte } func (m memStore) Header(height uint32) (btcwire.BlockHeader, bool) { header, ok := m.headers[height] return header, ok } func (m memStore) FilterHeader(height uint32) (chainhash.Hash, bool) { hash, ok := m.hashes[height] return hash, ok } func (m memStore) FilterHash(height uint32) (chainhash.Hash, bool) { hash, ok := m.hashes[height] return hash, ok } func (m memStore) Filter(height uint32) ([]byte, bool) { filter, ok := m.filters[height] return filter, ok } // TestExportFiltersUnboundedCount: a zero count means "as many as the byte budget allows", which // is what the channel asks for; treating it as zero records exported no filters at all. func TestExportFiltersUnboundedCount(t *testing.T) { store := memStore{ headers: map[uint32]btcwire.BlockHeader{}, hashes: map[uint32]chainhash.Hash{}, filters: map[uint32][]byte{}, } for height := uint32(1); height <= 3; height++ { var header btcwire.BlockHeader header.Version = int32(height) store.headers[height] = header store.filters[height] = []byte{byte(height)} store.hashes[height] = chainhash.Hash{byte(height)} } chunk, err := ExportFilters(store, 1, 0, 1<<20) if err != nil { t.Fatalf("ExportFilters: %v", err) } if chunk.Count != 3 || len(chunk.Payload) == 0 { t.Fatalf("exported %d filters", chunk.Count) } // The byte budget still bounds it. small, err := ExportFilters(store, 1, 0, 60) if err != nil { t.Fatalf("ExportFilters: %v", err) } if small.Count == 0 || small.Count >= 3 { t.Fatalf("a 60-byte budget exported %d filters", small.Count) } }