package store import ( "errors" "fmt" "os" "path/filepath" "sort" "sync" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) const ( // maxFileSize is where a new data file is started. A block appended // past it is stored whole, so the ceiling is soft by one block. maxFileSize = 512 * 1024 * 1024 // recHdrSize is 4 bytes of block length. There is no network field: the // store is chain-neutral, because a block's hash names the same bytes on // every chain that carries it. recHdrSize = 4 // indexRecSize is file (4), offset (4), length (4), hash (32). indexRecSize = 44 // tailName carries the newest index record, replaced atomically. tailName = "tail.dat" // formatName records the record format of the directory. formatName = "format" // FormatVersion is the record format this build writes and reads. Version // 1 had an 8-byte record header with the network in it; a directory still // in that format is refused rather than misread. FormatVersion = 2 ) // Store errors. // // The block store's names are kept as aliases of these: a caller that wants a // block, an error that explains a blob, and one spelling of each check. var ( ErrStoreClosed = errors.New("store: store is closed") ErrNotFound = errors.New("store: not found") ErrExists = errors.New("store: already exists") ErrCorruptFile = errors.New("store: a record does not commit to its key") ) // loc is where one blob's bytes live. type loc struct { FileNum uint32 Offset uint32 Len uint32 } // BlobStore is an append-only store of byte blobs keyed by a 32-byte key. // // It is btcd's ffldb shape cut down to one job: one data file per 512 MB, a // per-file index of where each blob lives, and a tail record that names the // newest blob whose append was durable. Two stores use it, block bodies and // filters, and the difference between them is how a blob is checked against its // key. // // It is safe for concurrent use. type BlobStore struct { mu sync.RWMutex dir string ext string verify func(chainhash.Hash, []byte) bool // trustIndex skips the open-time pass that reads every record back. trustIndex bool closed bool writeFile *os.File writeNum uint32 writeOff uint32 nextFileNum uint32 blobs map[chainhash.Hash]loc // Logf receives store diagnostics; nil discards them. Logf func(string, ...any) } // NewBlobStore opens or creates a store in dir whose data files carry ext. // // verify, when not nil, is asked whether a blob's bytes commit to its key: it // runs at write time and again at open, so a store cannot hold a blob that // does not belong to the name it is filed under. A nil verify stores bytes // whose check belongs to a caller that knows the relation, which is the filter // store: a filter is keyed by its block's hash and checked against its own // hash before it is put. // // The directory carries a format version. A directory written by a build that // put a network in every record header cannot be read correctly by this one, so // it is refused with the reason rather than parsed as if it could be: the // prefix is re-fetchable from peers, and a store that silently misreads its own // record headers is worse than one that says it cannot. func NewBlobStore(dir, ext string, verify func(chainhash.Hash, []byte) bool) (*BlobStore, error) { return newBlobStore(dir, ext, verify, false) } // NewBlobStoreTrusting is NewBlobStore without the pass that reads every stored // record back. See BlobStore.TrustIndex for what that pass is for and when // skipping it is sound. func NewBlobStoreTrusting(dir, ext string, verify func(chainhash.Hash, []byte) bool) (*BlobStore, error) { return newBlobStore(dir, ext, verify, true) } func newBlobStore(dir, ext string, verify func(chainhash.Hash, []byte) bool, trustIndex bool) (*BlobStore, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("store: create %s: %w", dir, err) } // A store with no verifier has nothing to check: the open-time pass would // read every record back and compare it against nothing. The filter store is // that case, and reading its 8 GB back on every open is the cost that made a // verification look like a hang. s := &BlobStore{ dir: dir, ext: ext, verify: verify, trustIndex: trustIndex || verify == nil, blobs: make(map[chainhash.Hash]loc), } if err := s.checkFormat(); err != nil { return nil, err } if err := s.loadIndex(); err != nil { return nil, err } return s, nil } // checkFormat reads the directory's format version, writes it for a new // directory, and refuses one from an older build. func (s *BlobStore) checkFormat() error { path := filepath.Join(s.dir, formatName) raw, err := os.ReadFile(path) if err == nil { var v int if _, err := fmt.Sscanf(string(raw), "%d", &v); err != nil { return fmt.Errorf("store: %s is %q, not a format version", path, raw) } if v != FormatVersion { return fmt.Errorf("store: %s is format %d, this build writes %d: delete it and re-fill, or use the build that wrote it", s.dir, v, FormatVersion) } return nil } if !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("store: read %s: %w", path, err) } // A directory with an index and no format is one written before the // version was recorded, which is the 8-byte-record format. if _, err := os.Stat(s.indexPath(0)); err == nil { return fmt.Errorf("store: %s holds blocks in the old 8-byte record format: delete it and re-fill", s.dir) } if err := os.WriteFile(path, []byte(fmt.Sprintf("%d\n", FormatVersion)), 0o644); err != nil { return fmt.Errorf("store: write %s: %w", path, err) } return nil } // Put appends a blob under its key. // // When the store has a verify function it runs before anything is written, so a // store cannot hold a blob that does not belong to the name it is filed under. func (s *BlobStore) Put(key chainhash.Hash, raw []byte) error { if len(raw) == 0 { return fmt.Errorf("store: a blob of 0 bytes") } if s.verify != nil && !s.verify(key, raw) { return fmt.Errorf("store: bytes of %d do not commit to %s", len(raw), key) } s.mu.Lock() defer s.mu.Unlock() if s.closed { return ErrStoreClosed } if _, ok := s.blobs[key]; ok { return ErrExists } if s.writeFile == nil || s.writeOff >= maxFileSize { if err := s.newFile(); err != nil { return err } } l := loc{FileNum: s.writeNum, Offset: s.writeOff, Len: uint32(len(raw))} if err := s.writeRecord(raw); err != nil { return err } s.writeOff += recHdrSize + uint32(len(raw)) if err := s.writeIndex(key, l); err != nil { return err } if err := s.writeTail(key, l); err != nil { return err } s.blobs[key] = l return nil } func (s *BlobStore) newFile() error { if s.writeFile != nil { if err := s.writeFile.Sync(); err != nil { return fmt.Errorf("store: sync %s: %w", s.writeFile.Name(), err) } if err := s.writeFile.Close(); err != nil { return fmt.Errorf("store: close %s: %w", s.writeFile.Name(), err) } } n := s.nextFileNum f, err := os.OpenFile(s.dataPath(n), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { return fmt.Errorf("store: open %s: %w", s.dataPath(n), err) } s.writeFile = f s.writeNum = n s.writeOff = 0 if n+1 > s.nextFileNum { s.nextFileNum = n + 1 } return nil } func (s *BlobStore) writeRecord(raw []byte) error { var hdr [recHdrSize]byte putUint32LE(hdr[0:4], uint32(len(raw))) if _, err := s.writeFile.Write(hdr[:]); err != nil { return fmt.Errorf("store: write: %w", err) } if _, err := s.writeFile.Write(raw); err != nil { return fmt.Errorf("store: write: %w", err) } return nil } func (s *BlobStore) writeIndex(hash chainhash.Hash, l loc) error { f, err := os.OpenFile(s.indexPath(l.FileNum), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { return fmt.Errorf("store: open %s: %w", s.indexPath(l.FileNum), err) } defer f.Close() rec := encodeIndex(hash, l) if _, err := f.Write(rec[:]); err != nil { return fmt.Errorf("store: write index: %w", err) } return nil } func (s *BlobStore) writeTail(hash chainhash.Hash, l loc) error { rec := encodeIndex(hash, l) tmp := filepath.Join(s.dir, tailName+".tmp") if err := os.WriteFile(tmp, rec[:], 0o644); err != nil { return fmt.Errorf("store: write tail: %w", err) } if err := os.Rename(tmp, filepath.Join(s.dir, tailName)); err != nil { return fmt.Errorf("store: replace tail: %w", err) } return nil } func (s *BlobStore) readTail() (chainhash.Hash, loc, bool) { raw, err := os.ReadFile(filepath.Join(s.dir, tailName)) if err != nil || len(raw) != indexRecSize { return chainhash.Hash{}, loc{}, false } return decodeIndex(raw) } // loadIndex rebuilds the block map from the index records and checks each // record against the data file it points at. // // The tail names the newest block whose append was durable. Every record up to // it must verify or the store refuses to open. The record after it is either a // block written before the tail replace could not land, or a torn append: it is // verified, kept if it verifies, and otherwise dropped with everything after // it, and the files are cut back to the last good block. func (s *BlobStore) loadIndex() error { type placed struct { hash chainhash.Hash loc loc } var all []placed var nums []uint32 for fileNum := uint32(0); ; fileNum++ { raw, err := os.ReadFile(s.indexPath(fileNum)) if errors.Is(err, os.ErrNotExist) { break } if err != nil { return fmt.Errorf("store: read index %d: %w", fileNum, err) } nums = append(nums, fileNum) for off := 0; off+indexRecSize <= len(raw); off += indexRecSize { hash, l, ok := decodeIndex(raw[off : off+indexRecSize]) if !ok { break } l.FileNum = fileNum all = append(all, placed{hash: hash, loc: l}) } } if len(all) == 0 { s.nextFileNum = 0 return nil } trusted := -1 hasTail := false if th, tl, ok := s.readTail(); ok { hasTail = true for i, p := range all { if p.hash == th && p.loc.FileNum == tl.FileNum && p.loc.Offset == tl.Offset && p.loc.Len == tl.Len { trusted = i break } } } if hasTail && trusted < 0 { return fmt.Errorf("%w: the tail names a block the index does not hold", ErrCorruptBlockFile) } for i, p := range all { if i <= trusted { if !s.trustIndex { if err := s.verifyLoc(p.hash, p.loc); err != nil { return err } } s.blobs[p.hash] = p.loc continue } if trusted == i-1 { // First record past the trusted run: an append whose tail replace // did not land, or a torn one. When the run has no tail at all this // is every record, which is the case trustIndex exists for. if s.trustIndex { s.blobs[p.hash] = p.loc trusted = i continue } if err := s.verifyLoc(p.hash, p.loc); err != nil { s.Logf("store: dropping a torn append at %s", p.hash) break } } s.blobs[p.hash] = p.loc trusted = i } if trusted < 0 { return nil } last := all[trusted] goodEnd := last.loc.Offset + recHdrSize + last.loc.Len if err := s.truncateAfter(last.loc.FileNum, goodEnd, trusted+1); err != nil { return err } s.writeNum = last.loc.FileNum s.writeOff = goodEnd s.nextFileNum = last.loc.FileNum + 1 if !hasTail { return s.writeTail(last.hash, last.loc) } return nil } // truncateAfter cuts the newest data file to goodEnd, removes index files above // fileNum, and trims fileNum's index to keepTotal records overall. func (s *BlobStore) truncateAfter(fileNum uint32, goodEnd uint32, keepTotal int) error { if fi, err := os.Stat(s.dataPath(fileNum)); err == nil && uint32(fi.Size()) > goodEnd { if err := os.Truncate(s.dataPath(fileNum), int64(goodEnd)); err != nil { return fmt.Errorf("store: truncate %s: %w", s.dataPath(fileNum), err) } } var files []uint32 for n := fileNum; ; n++ { if _, err := os.Stat(s.indexPath(n)); err != nil { break } files = append(files, n) } sort.Slice(files, func(i, j int) bool { return files[i] < files[j] }) for _, n := range files[:len(files)-1] { if err := os.Remove(s.indexPath(n)); err != nil { return fmt.Errorf("store: remove %s: %w", s.indexPath(n), err) } } fi, err := os.Stat(s.indexPath(fileNum)) if err != nil { return nil } if want := int64(keepTotal) * indexRecSize; fi.Size() > want { if err := os.Truncate(s.indexPath(fileNum), want); err != nil { return fmt.Errorf("store: truncate index %s: %w", s.indexPath(fileNum), err) } } return nil } // TrustIndex makes opening skip the pass that reads every stored record back. // // The pass is the store's integrity check: it finds a body that was altered // after it was written, which is what TestCorruptBlockRefused requires. It is // also linear in the store, so a 600 GB dataset takes hours to open, and a // daemon restart takes as long as the dataset is big. An operator who knows the // store's only writer is the instance itself can open it on the index alone; // reads still check the lengths they are handed. func (s *BlobStore) Trusted() bool { return s.trustIndex } // verifyLoc reads a block's header at its location and checks it against hash. func (s *BlobStore) verifyLoc(key chainhash.Hash, l loc) error { raw, err := s.readRaw(l) if err != nil { return err } if s.verify != nil && !s.verify(key, raw) { return fmt.Errorf("%w: %s", ErrCorruptFile, key) } return nil } // readRaw reads a block without consulting the map, which is what makes it the // read path for verification during load. func (s *BlobStore) readRaw(l loc) ([]byte, error) { f, err := os.Open(s.dataPath(l.FileNum)) if err != nil { return nil, fmt.Errorf("store: open %s: %w", s.dataPath(l.FileNum), err) } defer f.Close() var hdr [recHdrSize]byte if _, err := f.ReadAt(hdr[:], int64(l.Offset)); err != nil { return nil, fmt.Errorf("store: read header at %d: %w", l.Offset, err) } if n := getUint32LE(hdr[0:4]); n != l.Len { return nil, fmt.Errorf("%w: length %d at %d, index says %d", ErrCorruptBlockFile, n, l.Offset, l.Len) } buf := make([]byte, l.Len) if _, err := f.ReadAt(buf, int64(l.Offset+recHdrSize)); err != nil { return nil, fmt.Errorf("store: read block at %d: %w", l.Offset, err) } return buf, nil } func (s *BlobStore) dataPath(n uint32) string { return filepath.Join(s.dir, fmt.Sprintf("%08d.%s", n, s.ext)) } // indexPath names a file's index. Every store keeps .bidx, so a directory is // readable as its own kind by its data files alone. func (s *BlobStore) indexPath(n uint32) string { return filepath.Join(s.dir, fmt.Sprintf("%08d.bidx", n)) } // Get returns a blob's bytes after checking the length record; its key is // checked at write time and at open. func (s *BlobStore) Get(key chainhash.Hash) ([]byte, error) { s.mu.RLock() l, ok := s.blobs[key] s.mu.RUnlock() if !ok { return nil, ErrNotFound } return s.readRaw(l) } // Has reports whether a blob is stored. func (s *BlobStore) Has(key chainhash.Hash) bool { s.mu.RLock() defer s.mu.RUnlock() _, ok := s.blobs[key] return ok } // Len is the number of stored blobs. func (s *BlobStore) Len() int { s.mu.RLock() defer s.mu.RUnlock() return len(s.blobs) } // Close flushes and closes the write file. It is idempotent. func (s *BlobStore) Close() error { s.mu.Lock() defer s.mu.Unlock() if s.closed { return nil } s.closed = true if s.writeFile == nil { return nil } if err := s.writeFile.Sync(); err != nil { return fmt.Errorf("store: sync: %w", err) } return s.writeFile.Close() } func encodeIndex(hash chainhash.Hash, l loc) [indexRecSize]byte { var rec [indexRecSize]byte putUint32LE(rec[0:4], l.FileNum) putUint32LE(rec[4:8], l.Offset) putUint32LE(rec[8:12], l.Len) copy(rec[12:], hash[:]) return rec } func decodeIndex(rec []byte) (chainhash.Hash, loc, bool) { var hash chainhash.Hash l := loc{ FileNum: getUint32LE(rec[0:4]), Offset: getUint32LE(rec[4:8]), Len: getUint32LE(rec[8:12]), } copy(hash[:], rec[12:indexRecSize]) return hash, l, true } func putUint32LE(b []byte, v uint32) { b[0] = byte(v) b[1] = byte(v >> 8) b[2] = byte(v >> 16) b[3] = byte(v >> 24) } func getUint32LE(b []byte) uint32 { return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 }