blobstore.go raw

   1  package store
   2  
   3  import (
   4  	"errors"
   5  	"fmt"
   6  	"os"
   7  	"path/filepath"
   8  	"sort"
   9  	"sync"
  10  
  11  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  12  )
  13  
  14  const (
  15  	// maxFileSize is where a new data file is started. A block appended
  16  	// past it is stored whole, so the ceiling is soft by one block.
  17  	maxFileSize = 512 * 1024 * 1024
  18  	// recHdrSize is 4 bytes of block length. There is no network field: the
  19  	// store is chain-neutral, because a block's hash names the same bytes on
  20  	// every chain that carries it.
  21  	recHdrSize = 4
  22  	// indexRecSize is file (4), offset (4), length (4), hash (32).
  23  	indexRecSize = 44
  24  	// tailName carries the newest index record, replaced atomically.
  25  	tailName = "tail.dat"
  26  	// formatName records the record format of the directory.
  27  	formatName = "format"
  28  	// FormatVersion is the record format this build writes and reads. Version
  29  	// 1 had an 8-byte record header with the network in it; a directory still
  30  	// in that format is refused rather than misread.
  31  	FormatVersion = 2
  32  )
  33  
  34  // Store errors.
  35  //
  36  // The block store's names are kept as aliases of these: a caller that wants a
  37  // block, an error that explains a blob, and one spelling of each check.
  38  var (
  39  	ErrStoreClosed = errors.New("store: store is closed")
  40  	ErrNotFound    = errors.New("store: not found")
  41  	ErrExists      = errors.New("store: already exists")
  42  	ErrCorruptFile = errors.New("store: a record does not commit to its key")
  43  )
  44  
  45  // loc is where one blob's bytes live.
  46  type loc struct {
  47  	FileNum uint32
  48  	Offset  uint32
  49  	Len     uint32
  50  }
  51  
  52  // BlobStore is an append-only store of byte blobs keyed by a 32-byte key.
  53  //
  54  // It is btcd's ffldb shape cut down to one job: one data file per 512 MB, a
  55  // per-file index of where each blob lives, and a tail record that names the
  56  // newest blob whose append was durable. Two stores use it, block bodies and
  57  // filters, and the difference between them is how a blob is checked against its
  58  // key.
  59  //
  60  // It is safe for concurrent use.
  61  type BlobStore struct {
  62  	mu sync.RWMutex
  63  
  64  	dir string
  65  	ext string
  66  
  67  	verify func(chainhash.Hash, []byte) bool
  68  
  69  	// trustIndex skips the open-time pass that reads every record back.
  70  	trustIndex  bool
  71  	closed      bool
  72  	writeFile   *os.File
  73  	writeNum    uint32
  74  	writeOff    uint32
  75  	nextFileNum uint32
  76  
  77  	blobs map[chainhash.Hash]loc
  78  
  79  	// Logf receives store diagnostics; nil discards them.
  80  	Logf func(string, ...any)
  81  }
  82  
  83  // NewBlobStore opens or creates a store in dir whose data files carry ext.
  84  //
  85  // verify, when not nil, is asked whether a blob's bytes commit to its key: it
  86  // runs at write time and again at open, so a store cannot hold a blob that
  87  // does not belong to the name it is filed under. A nil verify stores bytes
  88  // whose check belongs to a caller that knows the relation, which is the filter
  89  // store: a filter is keyed by its block's hash and checked against its own
  90  // hash before it is put.
  91  //
  92  // The directory carries a format version. A directory written by a build that
  93  // put a network in every record header cannot be read correctly by this one, so
  94  // it is refused with the reason rather than parsed as if it could be: the
  95  // prefix is re-fetchable from peers, and a store that silently misreads its own
  96  // record headers is worse than one that says it cannot.
  97  func NewBlobStore(dir, ext string, verify func(chainhash.Hash, []byte) bool) (*BlobStore, error) {
  98  	return newBlobStore(dir, ext, verify, false)
  99  }
 100  
 101  // NewBlobStoreTrusting is NewBlobStore without the pass that reads every stored
 102  // record back. See BlobStore.TrustIndex for what that pass is for and when
 103  // skipping it is sound.
 104  func NewBlobStoreTrusting(dir, ext string, verify func(chainhash.Hash, []byte) bool) (*BlobStore, error) {
 105  	return newBlobStore(dir, ext, verify, true)
 106  }
 107  
 108  func newBlobStore(dir, ext string, verify func(chainhash.Hash, []byte) bool, trustIndex bool) (*BlobStore, error) {
 109  	if err := os.MkdirAll(dir, 0o755); err != nil {
 110  		return nil, fmt.Errorf("store: create %s: %w", dir, err)
 111  	}
 112  	// A store with no verifier has nothing to check: the open-time pass would
 113  	// read every record back and compare it against nothing. The filter store is
 114  	// that case, and reading its 8 GB back on every open is the cost that made a
 115  	// verification look like a hang.
 116  	s := &BlobStore{
 117  		dir: dir, ext: ext, verify: verify,
 118  		trustIndex: trustIndex || verify == nil,
 119  		blobs:      make(map[chainhash.Hash]loc),
 120  	}
 121  	if err := s.checkFormat(); err != nil {
 122  		return nil, err
 123  	}
 124  	if err := s.loadIndex(); err != nil {
 125  		return nil, err
 126  	}
 127  	return s, nil
 128  }
 129  
 130  // checkFormat reads the directory's format version, writes it for a new
 131  // directory, and refuses one from an older build.
 132  func (s *BlobStore) checkFormat() error {
 133  	path := filepath.Join(s.dir, formatName)
 134  	raw, err := os.ReadFile(path)
 135  	if err == nil {
 136  		var v int
 137  		if _, err := fmt.Sscanf(string(raw), "%d", &v); err != nil {
 138  			return fmt.Errorf("store: %s is %q, not a format version", path, raw)
 139  		}
 140  		if v != FormatVersion {
 141  			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)
 142  		}
 143  		return nil
 144  	}
 145  	if !errors.Is(err, os.ErrNotExist) {
 146  		return fmt.Errorf("store: read %s: %w", path, err)
 147  	}
 148  	// A directory with an index and no format is one written before the
 149  	// version was recorded, which is the 8-byte-record format.
 150  	if _, err := os.Stat(s.indexPath(0)); err == nil {
 151  		return fmt.Errorf("store: %s holds blocks in the old 8-byte record format: delete it and re-fill", s.dir)
 152  	}
 153  	if err := os.WriteFile(path, []byte(fmt.Sprintf("%d\n", FormatVersion)), 0o644); err != nil {
 154  		return fmt.Errorf("store: write %s: %w", path, err)
 155  	}
 156  	return nil
 157  }
 158  
 159  // Put appends a blob under its key.
 160  //
 161  // When the store has a verify function it runs before anything is written, so a
 162  // store cannot hold a blob that does not belong to the name it is filed under.
 163  func (s *BlobStore) Put(key chainhash.Hash, raw []byte) error {
 164  	if len(raw) == 0 {
 165  		return fmt.Errorf("store: a blob of 0 bytes")
 166  	}
 167  	if s.verify != nil && !s.verify(key, raw) {
 168  		return fmt.Errorf("store: bytes of %d do not commit to %s", len(raw), key)
 169  	}
 170  	s.mu.Lock()
 171  	defer s.mu.Unlock()
 172  	if s.closed {
 173  		return ErrStoreClosed
 174  	}
 175  	if _, ok := s.blobs[key]; ok {
 176  		return ErrExists
 177  	}
 178  	if s.writeFile == nil || s.writeOff >= maxFileSize {
 179  		if err := s.newFile(); err != nil {
 180  			return err
 181  		}
 182  	}
 183  	l := loc{FileNum: s.writeNum, Offset: s.writeOff, Len: uint32(len(raw))}
 184  	if err := s.writeRecord(raw); err != nil {
 185  		return err
 186  	}
 187  	s.writeOff += recHdrSize + uint32(len(raw))
 188  	if err := s.writeIndex(key, l); err != nil {
 189  		return err
 190  	}
 191  	if err := s.writeTail(key, l); err != nil {
 192  		return err
 193  	}
 194  	s.blobs[key] = l
 195  	return nil
 196  }
 197  
 198  func (s *BlobStore) newFile() error {
 199  	if s.writeFile != nil {
 200  		if err := s.writeFile.Sync(); err != nil {
 201  			return fmt.Errorf("store: sync %s: %w", s.writeFile.Name(), err)
 202  		}
 203  		if err := s.writeFile.Close(); err != nil {
 204  			return fmt.Errorf("store: close %s: %w", s.writeFile.Name(), err)
 205  		}
 206  	}
 207  	n := s.nextFileNum
 208  	f, err := os.OpenFile(s.dataPath(n), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
 209  	if err != nil {
 210  		return fmt.Errorf("store: open %s: %w", s.dataPath(n), err)
 211  	}
 212  	s.writeFile = f
 213  	s.writeNum = n
 214  	s.writeOff = 0
 215  	if n+1 > s.nextFileNum {
 216  		s.nextFileNum = n + 1
 217  	}
 218  	return nil
 219  }
 220  
 221  func (s *BlobStore) writeRecord(raw []byte) error {
 222  	var hdr [recHdrSize]byte
 223  	putUint32LE(hdr[0:4], uint32(len(raw)))
 224  	if _, err := s.writeFile.Write(hdr[:]); err != nil {
 225  		return fmt.Errorf("store: write: %w", err)
 226  	}
 227  	if _, err := s.writeFile.Write(raw); err != nil {
 228  		return fmt.Errorf("store: write: %w", err)
 229  	}
 230  	return nil
 231  }
 232  
 233  func (s *BlobStore) writeIndex(hash chainhash.Hash, l loc) error {
 234  	f, err := os.OpenFile(s.indexPath(l.FileNum), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
 235  	if err != nil {
 236  		return fmt.Errorf("store: open %s: %w", s.indexPath(l.FileNum), err)
 237  	}
 238  	defer f.Close()
 239  	rec := encodeIndex(hash, l)
 240  	if _, err := f.Write(rec[:]); err != nil {
 241  		return fmt.Errorf("store: write index: %w", err)
 242  	}
 243  	return nil
 244  }
 245  
 246  func (s *BlobStore) writeTail(hash chainhash.Hash, l loc) error {
 247  	rec := encodeIndex(hash, l)
 248  	tmp := filepath.Join(s.dir, tailName+".tmp")
 249  	if err := os.WriteFile(tmp, rec[:], 0o644); err != nil {
 250  		return fmt.Errorf("store: write tail: %w", err)
 251  	}
 252  	if err := os.Rename(tmp, filepath.Join(s.dir, tailName)); err != nil {
 253  		return fmt.Errorf("store: replace tail: %w", err)
 254  	}
 255  	return nil
 256  }
 257  
 258  func (s *BlobStore) readTail() (chainhash.Hash, loc, bool) {
 259  	raw, err := os.ReadFile(filepath.Join(s.dir, tailName))
 260  	if err != nil || len(raw) != indexRecSize {
 261  		return chainhash.Hash{}, loc{}, false
 262  	}
 263  	return decodeIndex(raw)
 264  }
 265  
 266  // loadIndex rebuilds the block map from the index records and checks each
 267  // record against the data file it points at.
 268  //
 269  // The tail names the newest block whose append was durable. Every record up to
 270  // it must verify or the store refuses to open. The record after it is either a
 271  // block written before the tail replace could not land, or a torn append: it is
 272  // verified, kept if it verifies, and otherwise dropped with everything after
 273  // it, and the files are cut back to the last good block.
 274  func (s *BlobStore) loadIndex() error {
 275  	type placed struct {
 276  		hash chainhash.Hash
 277  		loc  loc
 278  	}
 279  	var all []placed
 280  	var nums []uint32
 281  	for fileNum := uint32(0); ; fileNum++ {
 282  		raw, err := os.ReadFile(s.indexPath(fileNum))
 283  		if errors.Is(err, os.ErrNotExist) {
 284  			break
 285  		}
 286  		if err != nil {
 287  			return fmt.Errorf("store: read index %d: %w", fileNum, err)
 288  		}
 289  		nums = append(nums, fileNum)
 290  		for off := 0; off+indexRecSize <= len(raw); off += indexRecSize {
 291  			hash, l, ok := decodeIndex(raw[off : off+indexRecSize])
 292  			if !ok {
 293  				break
 294  			}
 295  			l.FileNum = fileNum
 296  			all = append(all, placed{hash: hash, loc: l})
 297  		}
 298  	}
 299  	if len(all) == 0 {
 300  		s.nextFileNum = 0
 301  		return nil
 302  	}
 303  
 304  	trusted := -1
 305  	hasTail := false
 306  	if th, tl, ok := s.readTail(); ok {
 307  		hasTail = true
 308  		for i, p := range all {
 309  			if p.hash == th && p.loc.FileNum == tl.FileNum && p.loc.Offset == tl.Offset && p.loc.Len == tl.Len {
 310  				trusted = i
 311  				break
 312  			}
 313  		}
 314  	}
 315  	if hasTail && trusted < 0 {
 316  		return fmt.Errorf("%w: the tail names a block the index does not hold", ErrCorruptBlockFile)
 317  	}
 318  	for i, p := range all {
 319  		if i <= trusted {
 320  			if !s.trustIndex {
 321  				if err := s.verifyLoc(p.hash, p.loc); err != nil {
 322  					return err
 323  				}
 324  			}
 325  			s.blobs[p.hash] = p.loc
 326  			continue
 327  		}
 328  		if trusted == i-1 {
 329  			// First record past the trusted run: an append whose tail replace
 330  			// did not land, or a torn one. When the run has no tail at all this
 331  			// is every record, which is the case trustIndex exists for.
 332  			if s.trustIndex {
 333  				s.blobs[p.hash] = p.loc
 334  				trusted = i
 335  				continue
 336  			}
 337  			if err := s.verifyLoc(p.hash, p.loc); err != nil {
 338  				s.Logf("store: dropping a torn append at %s", p.hash)
 339  				break
 340  			}
 341  		}
 342  		s.blobs[p.hash] = p.loc
 343  		trusted = i
 344  	}
 345  	if trusted < 0 {
 346  		return nil
 347  	}
 348  	last := all[trusted]
 349  	goodEnd := last.loc.Offset + recHdrSize + last.loc.Len
 350  	if err := s.truncateAfter(last.loc.FileNum, goodEnd, trusted+1); err != nil {
 351  		return err
 352  	}
 353  	s.writeNum = last.loc.FileNum
 354  	s.writeOff = goodEnd
 355  	s.nextFileNum = last.loc.FileNum + 1
 356  	if !hasTail {
 357  		return s.writeTail(last.hash, last.loc)
 358  	}
 359  	return nil
 360  }
 361  
 362  // truncateAfter cuts the newest data file to goodEnd, removes index files above
 363  // fileNum, and trims fileNum's index to keepTotal records overall.
 364  func (s *BlobStore) truncateAfter(fileNum uint32, goodEnd uint32, keepTotal int) error {
 365  	if fi, err := os.Stat(s.dataPath(fileNum)); err == nil && uint32(fi.Size()) > goodEnd {
 366  		if err := os.Truncate(s.dataPath(fileNum), int64(goodEnd)); err != nil {
 367  			return fmt.Errorf("store: truncate %s: %w", s.dataPath(fileNum), err)
 368  		}
 369  	}
 370  	var files []uint32
 371  	for n := fileNum; ; n++ {
 372  		if _, err := os.Stat(s.indexPath(n)); err != nil {
 373  			break
 374  		}
 375  		files = append(files, n)
 376  	}
 377  	sort.Slice(files, func(i, j int) bool { return files[i] < files[j] })
 378  	for _, n := range files[:len(files)-1] {
 379  		if err := os.Remove(s.indexPath(n)); err != nil {
 380  			return fmt.Errorf("store: remove %s: %w", s.indexPath(n), err)
 381  		}
 382  	}
 383  	fi, err := os.Stat(s.indexPath(fileNum))
 384  	if err != nil {
 385  		return nil
 386  	}
 387  	if want := int64(keepTotal) * indexRecSize; fi.Size() > want {
 388  		if err := os.Truncate(s.indexPath(fileNum), want); err != nil {
 389  			return fmt.Errorf("store: truncate index %s: %w", s.indexPath(fileNum), err)
 390  		}
 391  	}
 392  	return nil
 393  }
 394  
 395  // TrustIndex makes opening skip the pass that reads every stored record back.
 396  //
 397  // The pass is the store's integrity check: it finds a body that was altered
 398  // after it was written, which is what TestCorruptBlockRefused requires. It is
 399  // also linear in the store, so a 600 GB dataset takes hours to open, and a
 400  // daemon restart takes as long as the dataset is big. An operator who knows the
 401  // store's only writer is the instance itself can open it on the index alone;
 402  // reads still check the lengths they are handed.
 403  func (s *BlobStore) Trusted() bool { return s.trustIndex }
 404  
 405  // verifyLoc reads a block's header at its location and checks it against hash.
 406  func (s *BlobStore) verifyLoc(key chainhash.Hash, l loc) error {
 407  	raw, err := s.readRaw(l)
 408  	if err != nil {
 409  		return err
 410  	}
 411  	if s.verify != nil && !s.verify(key, raw) {
 412  		return fmt.Errorf("%w: %s", ErrCorruptFile, key)
 413  	}
 414  	return nil
 415  }
 416  
 417  // readRaw reads a block without consulting the map, which is what makes it the
 418  // read path for verification during load.
 419  func (s *BlobStore) readRaw(l loc) ([]byte, error) {
 420  	f, err := os.Open(s.dataPath(l.FileNum))
 421  	if err != nil {
 422  		return nil, fmt.Errorf("store: open %s: %w", s.dataPath(l.FileNum), err)
 423  	}
 424  	defer f.Close()
 425  	var hdr [recHdrSize]byte
 426  	if _, err := f.ReadAt(hdr[:], int64(l.Offset)); err != nil {
 427  		return nil, fmt.Errorf("store: read header at %d: %w", l.Offset, err)
 428  	}
 429  	if n := getUint32LE(hdr[0:4]); n != l.Len {
 430  		return nil, fmt.Errorf("%w: length %d at %d, index says %d", ErrCorruptBlockFile, n, l.Offset, l.Len)
 431  	}
 432  	buf := make([]byte, l.Len)
 433  	if _, err := f.ReadAt(buf, int64(l.Offset+recHdrSize)); err != nil {
 434  		return nil, fmt.Errorf("store: read block at %d: %w", l.Offset, err)
 435  	}
 436  	return buf, nil
 437  }
 438  
 439  func (s *BlobStore) dataPath(n uint32) string {
 440  	return filepath.Join(s.dir, fmt.Sprintf("%08d.%s", n, s.ext))
 441  }
 442  
 443  // indexPath names a file's index. Every store keeps .bidx, so a directory is
 444  // readable as its own kind by its data files alone.
 445  func (s *BlobStore) indexPath(n uint32) string {
 446  	return filepath.Join(s.dir, fmt.Sprintf("%08d.bidx", n))
 447  }
 448  
 449  // Get returns a blob's bytes after checking the length record; its key is
 450  // checked at write time and at open.
 451  func (s *BlobStore) Get(key chainhash.Hash) ([]byte, error) {
 452  	s.mu.RLock()
 453  	l, ok := s.blobs[key]
 454  	s.mu.RUnlock()
 455  	if !ok {
 456  		return nil, ErrNotFound
 457  	}
 458  	return s.readRaw(l)
 459  }
 460  
 461  // Has reports whether a blob is stored.
 462  func (s *BlobStore) Has(key chainhash.Hash) bool {
 463  	s.mu.RLock()
 464  	defer s.mu.RUnlock()
 465  	_, ok := s.blobs[key]
 466  	return ok
 467  }
 468  
 469  // Len is the number of stored blobs.
 470  func (s *BlobStore) Len() int {
 471  	s.mu.RLock()
 472  	defer s.mu.RUnlock()
 473  	return len(s.blobs)
 474  }
 475  
 476  // Close flushes and closes the write file. It is idempotent.
 477  func (s *BlobStore) Close() error {
 478  	s.mu.Lock()
 479  	defer s.mu.Unlock()
 480  	if s.closed {
 481  		return nil
 482  	}
 483  	s.closed = true
 484  	if s.writeFile == nil {
 485  		return nil
 486  	}
 487  	if err := s.writeFile.Sync(); err != nil {
 488  		return fmt.Errorf("store: sync: %w", err)
 489  	}
 490  	return s.writeFile.Close()
 491  }
 492  
 493  func encodeIndex(hash chainhash.Hash, l loc) [indexRecSize]byte {
 494  	var rec [indexRecSize]byte
 495  	putUint32LE(rec[0:4], l.FileNum)
 496  	putUint32LE(rec[4:8], l.Offset)
 497  	putUint32LE(rec[8:12], l.Len)
 498  	copy(rec[12:], hash[:])
 499  	return rec
 500  }
 501  
 502  func decodeIndex(rec []byte) (chainhash.Hash, loc, bool) {
 503  	var hash chainhash.Hash
 504  	l := loc{
 505  		FileNum: getUint32LE(rec[0:4]),
 506  		Offset:  getUint32LE(rec[4:8]),
 507  		Len:     getUint32LE(rec[8:12]),
 508  	}
 509  	copy(hash[:], rec[12:indexRecSize])
 510  	return hash, l, true
 511  }
 512  
 513  func putUint32LE(b []byte, v uint32) {
 514  	b[0] = byte(v)
 515  	b[1] = byte(v >> 8)
 516  	b[2] = byte(v >> 16)
 517  	b[3] = byte(v >> 24)
 518  }
 519  
 520  func getUint32LE(b []byte) uint32 {
 521  	return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
 522  }
 523