package store_test import ( "encoding/hex" "encoding/json" "errors" "os" "path/filepath" "runtime" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/store" ) type vector struct { BlockHash string `json:"blockHash"` Block string `json:"block"` } // blocks returns the official vector blocks as raw bytes keyed by the hash // their headers commit to. func blocks(t *testing.T) [][]byte { t.Helper() _, file, _, _ := runtime.Caller(0) raw, err := os.ReadFile(filepath.Join(filepath.Dir(file), "..", "..", "testdata", "bip158_testnet19.json")) if err != nil { t.Fatalf("read vectors: %v", err) } var vs []vector if err := json.Unmarshal(raw, &vs); err != nil { t.Fatalf("parse vectors: %v", err) } out := make([][]byte, 0, len(vs)) for _, v := range vs { b, err := hex.DecodeString(v.Block) if err != nil { t.Fatalf("decode: %v", err) } if chainhash.DoubleHashH(b[:80]).String() != v.BlockHash { t.Fatalf("vector block does not hash to its own %s", v.BlockHash) } out = append(out, b) } return out } func TestPutGetAndReopen(t *testing.T) { dir := t.TempDir() vs := blocks(t) s, err := store.NewBlockStore(dir) if err != nil { t.Fatalf("open: %v", err) } for i, raw := range vs { hash := chainhash.DoubleHashH(raw[:80]) if err := s.PutBlock(hash, raw); err != nil { t.Fatalf("put %d: %v", i, err) } } if err := s.PutBlock(chainhash.DoubleHashH(vs[0][:80]), vs[0]); !errors.Is(err, store.ErrBlockExists) { t.Fatalf("duplicate put: %v, want ErrBlockExists", err) } if err := s.PutBlock(chainhash.DoubleHashH(vs[1][:80]), vs[1]); err == nil { t.Fatalf("a block filed under another hash was accepted") } if err := s.Close(); err != nil { t.Fatalf("close: %v", err) } // Reopen: every block is found and its bytes verify against the hash it was // filed under. Heights are the caller's, not the store's: the chain's own // header store is what says which blocks are in it. s, err = store.NewBlockStore(dir) if err != nil { t.Fatalf("reopen: %v", err) } if s.Len() != len(vs) { t.Fatalf("reopened with %d blocks, want %d", s.Len(), len(vs)) } for i, raw := range vs { hash := chainhash.DoubleHashH(raw[:80]) got, err := s.GetBlock(hash) if err != nil { t.Fatalf("get %d: %v", i, err) } if string(got) != string(raw) { t.Fatalf("block %d bytes differ after reopen", i) } } // An append after reopen lands at the end of the last good block, so the // next reopen finds it too. s.Close() s, err = store.NewBlockStore(dir) if err != nil { t.Fatalf("second reopen: %v", err) } }