package store import ( "fmt" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // The block store's error names, which are the blob store's: a caller that asks // for a block reads the same errors it always did. var ( ErrBlockNotFound = ErrNotFound ErrBlockExists = ErrExists ErrCorruptBlockFile = ErrCorruptFile ) // BlockStore is a BlobStore whose keys are block hashes: a body is filed under // the hash its own header commits to, and a body that does not commit to the // name it arrives under is refused at write time and again at open. // // It knows nothing about chains or heights. The same block has one height on // each chain that carries it, so a height belongs to a header store and a body // belongs to its hash. type BlockStore struct{ *BlobStore } // NewBlockStore opens or creates a block store in dir, verifying that every // block on disk commits to the hash it is filed under. func NewBlockStore(dir string) (*BlockStore, error) { return newBlockStore(dir, false) } // NewBlockStoreTrusting is NewBlockStore without the open-time pass that reads // every block back. It is for an instance that is the store's only writer, on a // dataset big enough that the pass costs hours; a read still checks the length // it is handed. func NewBlockStoreTrusting(dir string) (*BlockStore, error) { return newBlockStore(dir, true) } func newBlockStore(dir string, trustIndex bool) (*BlockStore, error) { b, err := newBlobStore(dir, "blk", func(key chainhash.Hash, raw []byte) bool { return len(raw) >= btcwire.BlockHeaderSize && blockHash(raw) == key }, trustIndex) if err != nil { return nil, err } return &BlockStore{b}, nil } // PutBlock appends a raw block under the hash it commits to. func (s *BlockStore) PutBlock(hash chainhash.Hash, raw []byte) error { if len(raw) < btcwire.BlockHeaderSize { return fmt.Errorf("blockstore: block of %d bytes", len(raw)) } return s.Put(hash, raw) } // GetBlock returns a stored block's bytes. func (s *BlockStore) GetBlock(hash chainhash.Hash) ([]byte, error) { return s.Get(hash) } // HasBlock reports whether a block is stored. func (s *BlockStore) HasBlock(hash chainhash.Hash) bool { return s.Has(hash) } // blockHash is the hash a block's own header commits to: double SHA-256 of the // 80-byte header, or the fork's construction when the header carries the v2 // flag. It is what a body is filed under, so the store cannot be a store of // Bitcoin-form blocks only. func blockHash(raw []byte) chainhash.Hash { if len(raw) >= btcwire.BlockHeaderV2Size && getUint32LE(raw[0:4])&btcwire.HeaderV2Flag != 0 { var h btcwire.BlockHeader if err := h.DeserializeV2(raw[:btcwire.BlockHeaderV2Size]); err == nil { return h.BlockHash() } } return chainhash.DoubleHashH(raw[:80]) }