package chunk_test import ( "bytes" "encoding/binary" "testing" "git.smesh.lol/btcd-lite/internal/chunk" ) func collect(t *testing.T) (chunk.Recorder, *[]chunk.Chunk) { t.Helper() var got []chunk.Chunk return func(c chunk.Chunk) error { got = append(got, c); return nil }, &got } // TestCutHeadersDeterministic: the same header stream cut twice gives the same // boundaries and the same names, which is what makes two instances agree. func TestCutHeadersDeterministic(t *testing.T) { raw := make([]byte, 25*80) for i := range raw { raw[i] = byte(i * 7) } rec1, a := collect(t) n1, err := chunk.CutHeaders("btc", raw, 80, 0, 10, rec1) if err != nil || n1 != 3 { t.Fatalf("cut: %d %v", n1, err) } rec2, b := collect(t) if _, err := chunk.CutHeaders("btc", raw, 80, 0, 10, rec2); err != nil { t.Fatal(err) } if len(*a) != len(*b) { t.Fatalf("%d and %d chunks", len(*a), len(*b)) } for i := range *a { if (*a)[i].Name() != (*b)[i].Name() { t.Fatalf("chunk %d has two names", i) } } // The chunks tile the range with no gap and no repeat. next := uint32(0) for _, c := range *a { if c.From != next { t.Fatalf("run jumps from %d to %d", next, c.From) } next = c.To } if next != 25 { t.Fatalf("run ends at %d", next) } } // TestCutFiltersBudget: the byte budget, not the count, decides a cut, so a // busy block does not overflow a chunk and a quiet one does not waste one. func TestCutFiltersBudget(t *testing.T) { big := chunk.PackLengthPrefixed([][]byte{make([]byte, 400), make([]byte, 400), make([]byte, 400), make([]byte, 10)}) rec, got := collect(t) if _, err := chunk.CutLengthPrefixed("btc", chunk.Filters, big, 100, 1000, 1000, rec); err != nil { t.Fatal(err) } // Each 400-byte record is 404 on the wire and the budget is 1000, so two // fit a chunk and the third starts the next one. if len(*got) != 2 { t.Fatalf("%d chunks, want 2", len(*got)) } if (*got)[0].From != 100 || (*got)[0].To != 102 || (*got)[1].From != 102 || (*got)[1].To != 104 { t.Fatalf("boundaries %d-%d, %d-%d", (*got)[0].From, (*got)[0].To, (*got)[1].From, (*got)[1].To) } // A count cap cuts too, and a record bigger than the budget is a whole // chunk rather than an error. rec2, got2 := collect(t) one := chunk.PackLengthPrefixed([][]byte{make([]byte, 400)}) if _, err := chunk.CutLengthPrefixed("btc", chunk.Filters, one, 0, 10, 1000, rec2); err != nil || len(*got2) != 1 { t.Fatalf("oversized record: %d %v", len(*got2), err) } } // TestPackRoundTrip: pack then read back gives the same records. func TestPackRoundTrip(t *testing.T) { recs := [][]byte{{1, 2, 3}, {}, make([]byte, 300)} raw := chunk.PackLengthPrefixed(recs) at := 0 for _, want := range recs { n := int(binary.LittleEndian.Uint32(raw[at : at+4])) got := raw[at+4 : at+4+n] if !bytes.Equal(got, want) { t.Fatalf("record differs") } at += 4 + n } }