package store import ( "errors" "fmt" "os" "path/filepath" "sync" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/neutrino" ) // HeaderStore is neutrino's durable Store for one chain: the anchor, the header // chain, the filter hashes and filter headers, and the filters themselves. // // Everything it holds is committed by what is below it. A header is committed // by its parent and its proof of work, a filter hash and the filter header that // folds it are committed by the header chain once neutrino's core has accepted // them, and a filter is checked against its hash before it is put. So this // store repeats no validation: it is the disk, and the rules live in neutrino. // // Layout: one append-only record file of headers at their own width (80 bytes // for a Bitcoin header, 164 for the fork's version 2 form), with a length // prefix, plus three fixed-format files of 32-byte filter headers and filter // hashes addressed by height, and one append-only record file for the filters // (offset, length, height, hash, bytes). Truncate cuts all of them back, which // is what a reorg does. // // The header records are variable-width because the fork does not change the // header size everywhere: below its first version 2 height a chain's headers // are 80 bytes and above it they are 164, so one chain's file holds both forms // and the record's own length prefix is what says which. type HeaderStore struct { mu sync.RWMutex dir string headers *os.File fheaders *os.File fhashes *os.File filters *os.File filtersAt int64 anchor neutrino.Anchor hasAnchor bool // headerLocs is where each header record starts and how long it is, in // height order from the anchor: the index the file itself does not carry. // It is rebuilt by scanning the file on open, which is one pass over at // most a few hundred megabytes. headerLocs []headerLoc headerAtOff int64 fheaderCount uint32 fhashCount uint32 // filters by height. The store's chain is small in the number of heights // neutrino asks about at once relative to its block data, and a map keeps // the append path free of an index to maintain. It is rebuilt from the // record file on open. filterLocs map[uint32]filterLoc filterTip uint32 hasFilters bool } // headerLoc is one header record's position and width. type headerLoc struct { Offset uint32 Len uint32 } type filterLoc struct { Offset uint32 Len uint32 Hash chainhash.Hash } // headerFormatVersion is the header record format this build writes. Version 1 // was a fixed 80-byte record with no length prefix; a directory in that format // is refused rather than scanned, because every offset in it would be wrong. const headerFormatVersion = 2 const ( headersName = "headers.dat" fheadersName = "fheaders.dat" fhashesName = "fhashes.dat" filtersName = "filters.dat" anchorName = "anchor.json" ) // NewHeaderStore opens or creates the header store in dir. func NewHeaderStore(dir string) (*HeaderStore, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("headerstore: create %s: %w", dir, err) } s := &HeaderStore{dir: dir, filterLocs: make(map[uint32]filterLoc)} var err error if s.headers, err = os.OpenFile(filepath.Join(dir, headersName), os.O_CREATE|os.O_RDWR, 0o644); err != nil { return nil, fmt.Errorf("headerstore: %w", err) } if s.fheaders, err = os.OpenFile(filepath.Join(dir, fheadersName), os.O_CREATE|os.O_RDWR, 0o644); err != nil { return nil, fmt.Errorf("headerstore: %w", err) } if s.fhashes, err = os.OpenFile(filepath.Join(dir, fhashesName), os.O_CREATE|os.O_RDWR, 0o644); err != nil { return nil, fmt.Errorf("headerstore: %w", err) } if s.filters, err = os.OpenFile(filepath.Join(dir, filtersName), os.O_CREATE|os.O_RDWR, 0o644); err != nil { return nil, fmt.Errorf("headerstore: %w", err) } if err := s.checkFormat(); err != nil { return nil, err } if err := s.load(); err != nil { return nil, err } return s, nil } // checkFormat reads the directory's record format, writes it for a new // directory, and refuses one from an older build. func (s *HeaderStore) 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("headerstore: %s is %q, not a format version", path, raw) } if v != headerFormatVersion { return fmt.Errorf("headerstore: %s is header format %d, this build writes %d: delete it and re-sync, or use the build that wrote it", s.dir, v, headerFormatVersion) } return nil } if !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("headerstore: read %s: %w", path, err) } if fi, err := os.Stat(filepath.Join(s.dir, headersName)); err == nil && fi.Size() > 0 { return fmt.Errorf("headerstore: %s holds headers in the old fixed 80-byte record format: delete it and re-sync", s.dir) } if err := os.WriteFile(path, []byte(fmt.Sprintf("%d\n", headerFormatVersion)), 0o644); err != nil { return fmt.Errorf("headerstore: write %s: %w", path, err) } return nil } // load reads the counts from the file sizes and the anchor, and rebuilds the // filter locations. func (s *HeaderStore) load() error { if err := s.loadHeaders(); err != nil { return err } var err error s.fheaderCount, err = recordCount(s.fheaders, chainhash.HashSize) if err != nil { return err } s.fhashCount, err = recordCount(s.fhashes, chainhash.HashSize) if err != nil { return err } raw, err := os.ReadFile(filepath.Join(s.dir, anchorName)) if err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("headerstore: read anchor: %w", err) } if len(raw) > 0 { var a anchorJSON if err := a.decode(raw); err != nil { return err } s.anchor, err = a.toAnchor() if err != nil { return err } s.hasAnchor = true } return s.loadFilters() } // loadHeaders scans the header record file and indexes every record. A record // whose length prefix runs past the end of the file is a torn append and is cut // back; anything the reader cannot make sense of is an error. func (s *HeaderStore) loadHeaders() error { fi, err := s.headers.Stat() if err != nil { return err } size := fi.Size() var off int64 s.headerLocs = s.headerLocs[:0] hdr := make([]byte, 4) for off+4 <= size { if _, err := s.headers.ReadAt(hdr, off); err != nil { break } n := int64(getUint32LE(hdr)) if n <= 0 || off+4+n > size { break } s.headerLocs = append(s.headerLocs, headerLoc{Offset: uint32(off), Len: uint32(n)}) off += 4 + n } s.headerAtOff = off if off != size { if err := s.headers.Truncate(off); err != nil { return fmt.Errorf("headerstore: truncate headers: %w", err) } } return nil } // loadFilters walks the filter record file and checks every record's header // against its bytes as it goes, so a torn append at the end is the only thing // that can be dropped and anything else is an error. func (s *HeaderStore) loadFilters() error { fi, err := s.filters.Stat() if err != nil { return err } size := fi.Size() var off int64 for off+16 <= size { var rec [16]byte if _, err := s.filters.ReadAt(rec[:], off); err != nil { break } length := int64(getUint32LE(rec[0:4])) height := getUint32LE(rec[4:8]) var hash chainhash.Hash copy(hash[:], rec[8:16]) if off+16+length > size { break } buf := make([]byte, length) if _, err := s.filters.ReadAt(buf, off+16); err != nil { break } if chainhash.DoubleHashH(buf) != hash { if off+16+length == size { break } return fmt.Errorf("headerstore: filter at height %d does not commit to its hash", height) } s.filterLocs[height] = filterLoc{Offset: uint32(off), Len: uint32(length), Hash: hash} if !s.hasFilters || height > s.filterTip { s.filterTip = height s.hasFilters = true } off += 16 + length } s.filtersAt = off if off != size { if err := s.filters.Truncate(off); err != nil { return fmt.Errorf("headerstore: truncate filters: %w", err) } } return nil } func recordCount(f *os.File, size int64) (uint32, error) { fi, err := f.Stat() if err != nil { return 0, err } return uint32(fi.Size() / size), nil } // Anchor implements neutrino.Store. func (s *HeaderStore) Anchor() (neutrino.Anchor, bool) { s.mu.RLock() defer s.mu.RUnlock() return s.anchor, s.hasAnchor } // SetAnchor implements neutrino.Store. The anchor is written to disk before it // is returned as set, so a crash cannot leave a store that claims a chain it // does not start from. func (s *HeaderStore) SetAnchor(a neutrino.Anchor) error { s.mu.Lock() defer s.mu.Unlock() if s.hasAnchor { return errors.New("headerstore: anchor already set") } if a.BlockHash == (chainhash.Hash{}) { return errors.New("headerstore: anchor has no block hash") } if a.FilterHeight < -1 { return errors.New("headerstore: anchor filter height below -1") } raw, err := anchorJSONFrom(a).encode() if err != nil { return err } if err := writeFileAtomic(filepath.Join(s.dir, anchorName), raw); err != nil { return err } s.anchor = a s.hasAnchor = true return nil } // HeaderTip implements neutrino.Store. func (s *HeaderStore) HeaderTip() (uint32, chainhash.Hash, bool) { s.mu.RLock() defer s.mu.RUnlock() if !s.hasAnchor { return 0, chainhash.Hash{}, false } if len(s.headerLocs) == 0 { return s.anchor.Height, s.anchor.BlockHash, true } tip := s.anchor.Height + uint32(len(s.headerLocs)) - 1 h, ok := s.headerAtLocked(tip) if !ok { return 0, chainhash.Hash{}, false } return tip, h.BlockHash(), true } // Header implements neutrino.Store. func (s *HeaderStore) Header(height uint32) (btcwire.BlockHeader, bool) { s.mu.RLock() defer s.mu.RUnlock() return s.headerAtLocked(height) } func (s *HeaderStore) headerAtLocked(height uint32) (btcwire.BlockHeader, bool) { // Records are contiguous from the anchor height, so the record at a height // is the one at the offset from the anchor. if !s.hasAnchor || height < s.anchor.Height { return btcwire.BlockHeader{}, false } idx := height - s.anchor.Height if int(idx) >= len(s.headerLocs) { return btcwire.BlockHeader{}, false } l := s.headerLocs[idx] buf := make([]byte, l.Len) if _, err := s.headers.ReadAt(buf, int64(l.Offset)+4); err != nil { return btcwire.BlockHeader{}, false } var h btcwire.BlockHeader if err := h.DeserializeAny(buf); err != nil { return btcwire.BlockHeader{}, false } return h, true } // PutHeaders implements neutrino.Store. func (s *HeaderStore) PutHeaders(start uint32, headers []btcwire.BlockHeader) error { s.mu.Lock() defer s.mu.Unlock() if !s.hasAnchor { return errors.New("headerstore: no anchor") } // Records are contiguous from the anchor height. Neutrino seeds the genesis // header at the anchor height when the profile has no checkpoint, and every // other append follows the last record, so both paths land on the same rule: // the next record is the anchor height plus the record count. want := s.anchor.Height + uint32(len(s.headerLocs)) if len(s.headerLocs) > 0 && start <= s.anchor.Height { return fmt.Errorf("headerstore: headers start at %d, want one past the anchor", start) } if start != want { return fmt.Errorf("headerstore: headers start at %d, want %d", start, want) } // Each record is its own width, which is the header's: the fork's form is // wider, and one chain holds both either side of its first v2 height. var buf []byte locs := make([]headerLoc, 0, len(headers)) off := s.headerAtOff for i := range headers { enc := headers[i].SerializeAll() var pfx [4]byte putUint32LE(pfx[:], uint32(len(enc))) buf = append(buf, pfx[:]...) locs = append(locs, headerLoc{Offset: uint32(off), Len: uint32(len(enc))}) off += 4 + int64(len(enc)) buf = append(buf, enc...) } if _, err := s.headers.WriteAt(buf, s.headerAtOff); err != nil { return fmt.Errorf("headerstore: write headers: %w", err) } s.headerAtOff = off s.headerLocs = append(s.headerLocs, locs...) return nil } // FilterHeaderTip implements neutrino.Store. // // A store whose filters this instance built itself has no filter anchor: its // records are dense from height 0, so the tip is the last record. func (s *HeaderStore) FilterHeaderTip() (uint32, chainhash.Hash, bool) { s.mu.RLock() defer s.mu.RUnlock() if !s.hasAnchor { return 0, chainhash.Hash{}, false } if s.anchor.FilterHeight < 0 { if s.fheaderCount == 0 { return 0, chainhash.Hash{}, false } tip := s.fheaderCount - 1 h, ok := s.fheaderAtLocked(tip) if !ok { return 0, chainhash.Hash{}, false } return tip, h, true } anchorH := uint32(s.anchor.FilterHeight) if s.fheaderCount == 0 { return anchorH, s.anchor.FilterHeader, true } tip := anchorH + s.fheaderCount h, ok := s.fheaderAtLocked(tip) if !ok { return 0, chainhash.Hash{}, false } return tip, h, true } // FilterHeader implements neutrino.Store. The anchor height's header is the // anchor's; the records start at the next height. func (s *HeaderStore) FilterHeader(height uint32) (chainhash.Hash, bool) { s.mu.RLock() defer s.mu.RUnlock() if !s.hasAnchor { return chainhash.Hash{}, false } if s.anchor.FilterHeight < 0 { return s.fheaderAtLocked(height) } if height == uint32(s.anchor.FilterHeight) { return s.anchor.FilterHeader, true } return s.fheaderAtLocked(height) } func (s *HeaderStore) fheaderAtLocked(height uint32) (chainhash.Hash, bool) { if !s.hasAnchor { return chainhash.Hash{}, false } if s.anchor.FilterHeight < 0 { // Dense: record i is height i. if height >= s.fheaderCount { return chainhash.Hash{}, false } var h chainhash.Hash if _, err := s.fheaders.ReadAt(h[:], int64(height)*chainhash.HashSize); err != nil { return chainhash.Hash{}, false } return h, true } anchorH := uint32(s.anchor.FilterHeight) if height <= anchorH || height-anchorH > s.fheaderCount { return chainhash.Hash{}, false } var h chainhash.Hash if _, err := s.fheaders.ReadAt(h[:], int64(height-anchorH-1)*chainhash.HashSize); err != nil { return chainhash.Hash{}, false } return h, true } // FilterHash implements neutrino.Store. func (s *HeaderStore) FilterHash(height uint32) (chainhash.Hash, bool) { s.mu.RLock() defer s.mu.RUnlock() if !s.hasAnchor { return chainhash.Hash{}, false } if s.anchor.FilterHeight < 0 { // Dense: record i is height i. if height >= s.fhashCount { return chainhash.Hash{}, false } var h chainhash.Hash if _, err := s.fhashes.ReadAt(h[:], int64(height)*chainhash.HashSize); err != nil { return chainhash.Hash{}, false } return h, true } anchorH := uint32(s.anchor.FilterHeight) if height <= anchorH || height-anchorH-1 >= s.fhashCount { return chainhash.Hash{}, false } var h chainhash.Hash if _, err := s.fhashes.ReadAt(h[:], int64(height-anchorH-1)*chainhash.HashSize); err != nil { return chainhash.Hash{}, false } return h, true } // PutFilterHeaders implements neutrino.Store. The two slices are parallel; the // caller has already verified the fold. func (s *HeaderStore) PutFilterHeaders(start uint32, filterHashes, filterHeaders []chainhash.Hash) error { s.mu.Lock() defer s.mu.Unlock() if !s.hasAnchor || s.anchor.FilterHeight < 0 { return errors.New("headerstore: no filter header anchor") } if len(filterHashes) != len(filterHeaders) { return errors.New("headerstore: filter hashes and headers differ in length") } // The anchor height's filter header is not a record, so the first record is // at the anchor height plus one. anchorH := uint32(s.anchor.FilterHeight) want := anchorH + 1 + s.fhashCount if start != want { return fmt.Errorf("headerstore: filter headers start at %d, want %d", start, want) } fh := make([]byte, 0, len(filterHashes)*chainhash.HashSize) for _, h := range filterHashes { fh = append(fh, h[:]...) } if _, err := s.fhashes.WriteAt(fh, int64(s.fhashCount)*chainhash.HashSize); err != nil { return fmt.Errorf("headerstore: write filter hashes: %w", err) } hh := make([]byte, 0, len(filterHeaders)*chainhash.HashSize) for _, h := range filterHeaders { hh = append(hh, h[:]...) } if _, err := s.fheaders.WriteAt(hh, int64(s.fheaderCount)*chainhash.HashSize); err != nil { return fmt.Errorf("headerstore: write filter headers: %w", err) } s.fhashCount += uint32(len(filterHashes)) s.fheaderCount += uint32(len(filterHeaders)) return nil } // PutFilterHeaderRecord appends the filter hash and its folded header at a // height, for a chain whose filters this instance builds itself. // // A store has one mode. Neutrino's PutFilterHeaders writes records from the // anchor's filter height plus one, because its fold starts from a filter header // the anchor names; a self-built fold starts at height 0 with a zero previous // header, so its records are dense from 0 and there is no filter anchor. A // store that has one cannot take the other, and says so rather than writing a // file two readers would interpret differently. func (s *HeaderStore) PutFilterHeaderRecord(height uint32, filterHash, filterHeader chainhash.Hash) error { s.mu.Lock() defer s.mu.Unlock() if !s.hasAnchor { return errors.New("headerstore: no anchor") } if s.anchor.FilterHeight >= 0 { return fmt.Errorf("headerstore: filter headers come from the anchor at %d; a built fold cannot append to them", s.anchor.FilterHeight) } if height != s.fhashCount { return fmt.Errorf("headerstore: filter header at %d, want %d", height, s.fhashCount) } if _, err := s.fhashes.WriteAt(filterHash[:], int64(s.fhashCount)*chainhash.HashSize); err != nil { return fmt.Errorf("headerstore: write filter hash: %w", err) } if _, err := s.fheaders.WriteAt(filterHeader[:], int64(s.fheaderCount)*chainhash.HashSize); err != nil { return fmt.Errorf("headerstore: write filter header: %w", err) } s.fhashCount++ s.fheaderCount++ return nil } // FilterTip implements neutrino.Store. func (s *HeaderStore) FilterTip() (uint32, bool) { s.mu.RLock() defer s.mu.RUnlock() return s.filterTip, s.hasFilters } // Filter implements neutrino.Store. func (s *HeaderStore) Filter(height uint32) ([]byte, bool) { s.mu.RLock() loc, ok := s.filterLocs[height] s.mu.RUnlock() if !ok { return nil, false } buf := make([]byte, loc.Len) if _, err := s.filters.ReadAt(buf, int64(loc.Offset)+16); err != nil { return nil, false } return buf, true } // PutFilter implements neutrino.Store. The bytes are hashed and compared with // the hash the caller says the header chain commits to, so a filter that does // not verify cannot enter the store through this door either. func (s *HeaderStore) PutFilter(height uint32, blockHash, filterHash chainhash.Hash, filter []byte) error { if got := chainhash.DoubleHashH(filter); got != filterHash { return fmt.Errorf("headerstore: filter at %d hashes to %s, not %s", height, got, filterHash) } s.mu.Lock() defer s.mu.Unlock() if _, ok := s.filterLocs[height]; ok { return nil } var rec [16]byte putUint32LE(rec[0:4], uint32(len(filter))) putUint32LE(rec[4:8], height) copy(rec[8:16], filterHash[:]) off := s.filtersAt if _, err := s.filters.WriteAt(rec[:], off); err != nil { return fmt.Errorf("headerstore: write filter record: %w", err) } if _, err := s.filters.WriteAt(filter, off+16); err != nil { return fmt.Errorf("headerstore: write filter: %w", err) } s.filtersAt = off + 16 + int64(len(filter)) s.filterLocs[height] = filterLoc{Offset: uint32(off), Len: uint32(len(filter)), Hash: filterHash} if !s.hasFilters || height > s.filterTip { s.filterTip = height s.hasFilters = true } _ = blockHash return nil } // Truncate implements neutrino.Store: it drops every header, filter header, // filter hash and filter at or above from. func (s *HeaderStore) Truncate(from uint32) error { s.mu.Lock() defer s.mu.Unlock() if !s.hasAnchor { return errors.New("headerstore: no anchor") } if from <= s.anchor.Height { return fmt.Errorf("headerstore: truncate at %d is at or below the anchor", from) } // Records are contiguous from the anchor height, so from keeps the records // for the heights below it. { keep := uint32(from - s.anchor.Height) if int(keep) < len(s.headerLocs) { cut := int64(s.headerLocs[keep].Offset) if err := s.headers.Truncate(cut); err != nil { return fmt.Errorf("headerstore: truncate headers: %w", err) } s.headerLocs = s.headerLocs[:keep] s.headerAtOff = cut } } if s.anchor.FilterHeight < 0 { // Dense records: from keeps the records for heights below it, and // there is no anchor record to preserve. keep := int64(from) * chainhash.HashSize if keep < int64(s.fhashCount)*chainhash.HashSize { if err := s.fhashes.Truncate(keep); err != nil { return fmt.Errorf("headerstore: truncate filter hashes: %w", err) } if err := s.fheaders.Truncate(keep); err != nil { return fmt.Errorf("headerstore: truncate filter headers: %w", err) } s.fhashCount = uint32(keep / chainhash.HashSize) s.fheaderCount = s.fhashCount } } if s.anchor.FilterHeight >= 0 { // Filter header records start at the anchor height plus one, so from // keeps the records for heights below it. var keepRecords int64 if from > uint32(s.anchor.FilterHeight)+1 { keepRecords = int64(from-uint32(s.anchor.FilterHeight)-1) * chainhash.HashSize } if keepRecords < int64(s.fhashCount)*chainhash.HashSize { if err := s.fhashes.Truncate(keepRecords); err != nil { return fmt.Errorf("headerstore: truncate filter hashes: %w", err) } if err := s.fheaders.Truncate(keepRecords); err != nil { return fmt.Errorf("headerstore: truncate filter headers: %w", err) } s.fhashCount = uint32(keepRecords / chainhash.HashSize) s.fheaderCount = s.fhashCount } } // Filters at or above from go, and since they are appended in height order // the file can be cut at the first one dropped. var first int64 = -1 for h, loc := range s.filterLocs { if h >= from && (first < 0 || int64(loc.Offset) < first) { first = int64(loc.Offset) } } if first >= 0 { if err := s.filters.Truncate(first); err != nil { return fmt.Errorf("headerstore: truncate filters: %w", err) } s.filtersAt = first } for h := range s.filterLocs { if h >= from { delete(s.filterLocs, h) } } s.hasFilters = false s.filterTip = 0 for h := range s.filterLocs { if !s.hasFilters || h > s.filterTip { s.filterTip = h s.hasFilters = true } } return nil } // Close closes the files. func (s *HeaderStore) Close() error { s.mu.Lock() defer s.mu.Unlock() var errs []error for _, f := range []*os.File{s.headers, s.fheaders, s.fhashes, s.filters} { if f == nil { continue } if err := f.Sync(); err != nil { errs = append(errs, err) } if err := f.Close(); err != nil { errs = append(errs, err) } } return errors.Join(errs...) } // anchorJSON is the on-disk anchor. type anchorJSON struct { Height uint32 `json:"height"` BlockHash string `json:"block_hash"` FilterHeight int32 `json:"filter_height"` FilterHeader string `json:"filter_header"` } func anchorJSONFrom(a neutrino.Anchor) anchorJSON { return anchorJSON{ Height: a.Height, BlockHash: a.BlockHash.String(), FilterHeight: a.FilterHeight, FilterHeader: a.FilterHeader.String(), } } func (a anchorJSON) encode() ([]byte, error) { return jsonMarshal(a) } func (a *anchorJSON) decode(raw []byte) error { return jsonUnmarshal(raw, a) } func (a anchorJSON) toAnchor() (neutrino.Anchor, error) { bh, err := chainhash.NewHashFromStr(a.BlockHash) if err != nil { return neutrino.Anchor{}, fmt.Errorf("headerstore: anchor block hash: %w", err) } var fh chainhash.Hash if a.FilterHeight >= 0 { f, err := chainhash.NewHashFromStr(a.FilterHeader) if err != nil { return neutrino.Anchor{}, fmt.Errorf("headerstore: anchor filter header: %w", err) } fh = *f } return neutrino.Anchor{Height: a.Height, BlockHash: *bh, FilterHeight: a.FilterHeight, FilterHeader: fh}, nil }