package store import ( "os" "path/filepath" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // fakeBlock makes a block whose header hashes to a unique value for i, and // whose 80-byte header never changes once made. func fakeBlock(i byte) []byte { b := make([]byte, 80+10) b[0] = i b[1] = i b[79] = i return b } // TestAppendAcrossReopen writes one block, closes the store and reopens it, for // five blocks: the restart order, which is what a VPS restart actually is. func TestAppendAcrossReopen(t *testing.T) { dir := t.TempDir() var last chainhash.Hash for i := 0; i < 5; i++ { s, err := NewBlockStore(dir) if err != nil { t.Fatalf("open %d: %v", i, err) } if s.Len() != i { t.Fatalf("open %d sees %d blocks", i, s.Len()) } raw := fakeBlock(byte(i + 1)) last = chainhash.DoubleHashH(raw[:80]) if err := s.PutBlock(last, raw); err != nil { t.Fatalf("put %d: %v", i, err) } if err := s.Close(); err != nil { t.Fatalf("close %d: %v", i, err) } } s, err := NewBlockStore(dir) if err != nil { t.Fatal(err) } defer s.Close() if s.Len() != 5 { t.Fatalf("final len %d", s.Len()) } raw, err := s.GetBlock(last) if err != nil || string(raw) != string(fakeBlock(5)) { t.Fatalf("last block: %v", err) } } // TestTailAbsentKeepsOnlyVerifiedBlocks drops the tail file, which is what a // crash before the first tail write leaves, and requires the store to adopt the // blocks it can verify rather than forget them. func TestTailAbsent(t *testing.T) { dir := t.TempDir() s, err := NewBlockStore(dir) if err != nil { t.Fatal(err) } for i := byte(1); i <= 3; i++ { raw := fakeBlock(i) if err := s.PutBlock(chainhash.DoubleHashH(raw[:80]), raw); err != nil { t.Fatal(err) } } s.Close() if err := removeFile(dir, tailName); err != nil { t.Fatal(err) } s, err = NewBlockStore(dir) if err != nil { t.Fatalf("open without tail: %v", err) } if s.Len() != 3 { t.Fatalf("without tail: %d blocks, want 3", s.Len()) } // The tail is rewritten, so the next open is the strict path. s.Close() s, err = NewBlockStore(dir) if err != nil { t.Fatalf("reopen after rewrite: %v", err) } if s.Len() != 3 { t.Fatalf("after rewrite: %d blocks", s.Len()) } } func removeFile(dir, name string) error { return os.Remove(filepath.Join(dir, name)) }