package store_test import ( "os" "path/filepath" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/store" ) // dataFile returns the path of the store's only data file. func dataFile(t *testing.T, dir string) string { t.Helper() matches, err := filepath.Glob(filepath.Join(dir, "*.blk")) if err != nil || len(matches) != 1 { t.Fatalf("data files: %v %v", matches, err) } return matches[0] } // TestTornWriteIsDropped appends bytes past the last good block, the shape a // crash mid-append leaves, and requires the store to open with every good // block and the next append at the last good block's end. func TestTornWriteIsDropped(t *testing.T) { dir := t.TempDir() vs := blocks(t) hashOf := func(raw []byte) chainhash.Hash { return chainhash.DoubleHashH(raw[:80]) } s, err := store.NewBlockStore(dir) if err != nil { t.Fatal(err) } for _, raw := range vs[:3] { if err := s.PutBlock(hashOf(raw), raw); err != nil { t.Fatal(err) } } if err := s.Close(); err != nil { t.Fatal(err) } goodSize, err := os.Stat(dataFile(t, dir)) if err != nil { t.Fatal(err) } f, err := os.OpenFile(dataFile(t, dir), os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { t.Fatal(err) } // Half a record header and a few bytes of a block. if _, err := f.Write([]byte{1, 2, 3, 4, 5}); err != nil { t.Fatal(err) } f.Close() s, err = store.NewBlockStore(dir) if err != nil { t.Fatalf("open after torn write: %v", err) } if s.Len() != 3 { t.Fatalf("blocks after torn write: %d, want 3", s.Len()) } if fi, err := os.Stat(dataFile(t, dir)); err != nil || fi.Size() != goodSize.Size() { t.Fatalf("data file size %v (err %v), want %d", fi.Size(), err, goodSize.Size()) } // The append that follows goes to the right place and survives reopen. if err := s.PutBlock(hashOf(vs[3]), vs[3]); err != nil { t.Fatalf("append after repair: %v", err) } if err := s.Close(); err != nil { t.Fatal(err) } s, err = store.NewBlockStore(dir) if err != nil { t.Fatal(err) } if s.Len() != 4 { t.Fatalf("blocks after post-repair reopen: %d, want 4", s.Len()) } if got, err := s.GetBlock(hashOf(vs[3])); err != nil || string(got) != string(vs[3]) { t.Fatalf("post-repair block read: %v", err) } } // TestCorruptBlockRefused requires a record whose bytes do not commit to its // hash to stop the store rather than be served. func TestCorruptBlockRefused(t *testing.T) { dir := t.TempDir() vs := blocks(t) s, err := store.NewBlockStore(dir) if err != nil { t.Fatal(err) } if err := s.PutBlock(chainhash.DoubleHashH(vs[0][:80]), vs[0]); err != nil { t.Fatal(err) } s.Close() // Flip one byte of the stored block body. f, err := os.OpenFile(dataFile(t, dir), os.O_WRONLY, 0o644) if err != nil { t.Fatal(err) } if _, err := f.WriteAt([]byte{0xff}, 8+10); err != nil { t.Fatal(err) } f.Close() if _, err := store.NewBlockStore(dir); err == nil { t.Fatal("a store with a block that does not commit to its hash opened") } }