headerstore.go raw
1 package store
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7 "path/filepath"
8 "sync"
9
10 "git.smesh.lol/nostrino/pkg/btcwire"
11 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
12 "git.smesh.lol/nostrino/pkg/neutrino"
13 )
14
15 // HeaderStore is neutrino's durable Store for one chain: the anchor, the header
16 // chain, the filter hashes and filter headers, and the filters themselves.
17 //
18 // Everything it holds is committed by what is below it. A header is committed
19 // by its parent and its proof of work, a filter hash and the filter header that
20 // folds it are committed by the header chain once neutrino's core has accepted
21 // them, and a filter is checked against its hash before it is put. So this
22 // store repeats no validation: it is the disk, and the rules live in neutrino.
23 //
24 // Layout: one append-only record file of headers at their own width (80 bytes
25 // for a Bitcoin header, 164 for the fork's version 2 form), with a length
26 // prefix, plus three fixed-format files of 32-byte filter headers and filter
27 // hashes addressed by height, and one append-only record file for the filters
28 // (offset, length, height, hash, bytes). Truncate cuts all of them back, which
29 // is what a reorg does.
30 //
31 // The header records are variable-width because the fork does not change the
32 // header size everywhere: below its first version 2 height a chain's headers
33 // are 80 bytes and above it they are 164, so one chain's file holds both forms
34 // and the record's own length prefix is what says which.
35 type HeaderStore struct {
36 mu sync.RWMutex
37
38 dir string
39 headers *os.File
40 fheaders *os.File
41 fhashes *os.File
42 filters *os.File
43 filtersAt int64
44
45 anchor neutrino.Anchor
46 hasAnchor bool
47
48 // headerLocs is where each header record starts and how long it is, in
49 // height order from the anchor: the index the file itself does not carry.
50 // It is rebuilt by scanning the file on open, which is one pass over at
51 // most a few hundred megabytes.
52 headerLocs []headerLoc
53 headerAtOff int64
54 fheaderCount uint32
55 fhashCount uint32
56
57 // filters by height. The store's chain is small in the number of heights
58 // neutrino asks about at once relative to its block data, and a map keeps
59 // the append path free of an index to maintain. It is rebuilt from the
60 // record file on open.
61 filterLocs map[uint32]filterLoc
62 filterTip uint32
63 hasFilters bool
64 }
65
66 // headerLoc is one header record's position and width.
67 type headerLoc struct {
68 Offset uint32
69 Len uint32
70 }
71
72 type filterLoc struct {
73 Offset uint32
74 Len uint32
75 Hash chainhash.Hash
76 }
77
78 // headerFormatVersion is the header record format this build writes. Version 1
79 // was a fixed 80-byte record with no length prefix; a directory in that format
80 // is refused rather than scanned, because every offset in it would be wrong.
81 const headerFormatVersion = 2
82
83 const (
84 headersName = "headers.dat"
85 fheadersName = "fheaders.dat"
86 fhashesName = "fhashes.dat"
87 filtersName = "filters.dat"
88 anchorName = "anchor.json"
89 )
90
91 // NewHeaderStore opens or creates the header store in dir.
92 func NewHeaderStore(dir string) (*HeaderStore, error) {
93 if err := os.MkdirAll(dir, 0o755); err != nil {
94 return nil, fmt.Errorf("headerstore: create %s: %w", dir, err)
95 }
96 s := &HeaderStore{dir: dir, filterLocs: make(map[uint32]filterLoc)}
97 var err error
98 if s.headers, err = os.OpenFile(filepath.Join(dir, headersName), os.O_CREATE|os.O_RDWR, 0o644); err != nil {
99 return nil, fmt.Errorf("headerstore: %w", err)
100 }
101 if s.fheaders, err = os.OpenFile(filepath.Join(dir, fheadersName), os.O_CREATE|os.O_RDWR, 0o644); err != nil {
102 return nil, fmt.Errorf("headerstore: %w", err)
103 }
104 if s.fhashes, err = os.OpenFile(filepath.Join(dir, fhashesName), os.O_CREATE|os.O_RDWR, 0o644); err != nil {
105 return nil, fmt.Errorf("headerstore: %w", err)
106 }
107 if s.filters, err = os.OpenFile(filepath.Join(dir, filtersName), os.O_CREATE|os.O_RDWR, 0o644); err != nil {
108 return nil, fmt.Errorf("headerstore: %w", err)
109 }
110 if err := s.checkFormat(); err != nil {
111 return nil, err
112 }
113 if err := s.load(); err != nil {
114 return nil, err
115 }
116 return s, nil
117 }
118
119 // checkFormat reads the directory's record format, writes it for a new
120 // directory, and refuses one from an older build.
121 func (s *HeaderStore) checkFormat() error {
122 path := filepath.Join(s.dir, formatName)
123 raw, err := os.ReadFile(path)
124 if err == nil {
125 var v int
126 if _, err := fmt.Sscanf(string(raw), "%d", &v); err != nil {
127 return fmt.Errorf("headerstore: %s is %q, not a format version", path, raw)
128 }
129 if v != headerFormatVersion {
130 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)
131 }
132 return nil
133 }
134 if !errors.Is(err, os.ErrNotExist) {
135 return fmt.Errorf("headerstore: read %s: %w", path, err)
136 }
137 if fi, err := os.Stat(filepath.Join(s.dir, headersName)); err == nil && fi.Size() > 0 {
138 return fmt.Errorf("headerstore: %s holds headers in the old fixed 80-byte record format: delete it and re-sync", s.dir)
139 }
140 if err := os.WriteFile(path, []byte(fmt.Sprintf("%d\n", headerFormatVersion)), 0o644); err != nil {
141 return fmt.Errorf("headerstore: write %s: %w", path, err)
142 }
143 return nil
144 }
145
146 // load reads the counts from the file sizes and the anchor, and rebuilds the
147 // filter locations.
148 func (s *HeaderStore) load() error {
149 if err := s.loadHeaders(); err != nil {
150 return err
151 }
152 var err error
153 s.fheaderCount, err = recordCount(s.fheaders, chainhash.HashSize)
154 if err != nil {
155 return err
156 }
157 s.fhashCount, err = recordCount(s.fhashes, chainhash.HashSize)
158 if err != nil {
159 return err
160 }
161 raw, err := os.ReadFile(filepath.Join(s.dir, anchorName))
162 if err != nil && !errors.Is(err, os.ErrNotExist) {
163 return fmt.Errorf("headerstore: read anchor: %w", err)
164 }
165 if len(raw) > 0 {
166 var a anchorJSON
167 if err := a.decode(raw); err != nil {
168 return err
169 }
170 s.anchor, err = a.toAnchor()
171 if err != nil {
172 return err
173 }
174 s.hasAnchor = true
175 }
176 return s.loadFilters()
177 }
178
179 // loadHeaders scans the header record file and indexes every record. A record
180 // whose length prefix runs past the end of the file is a torn append and is cut
181 // back; anything the reader cannot make sense of is an error.
182 func (s *HeaderStore) loadHeaders() error {
183 fi, err := s.headers.Stat()
184 if err != nil {
185 return err
186 }
187 size := fi.Size()
188 var off int64
189 s.headerLocs = s.headerLocs[:0]
190 hdr := make([]byte, 4)
191 for off+4 <= size {
192 if _, err := s.headers.ReadAt(hdr, off); err != nil {
193 break
194 }
195 n := int64(getUint32LE(hdr))
196 if n <= 0 || off+4+n > size {
197 break
198 }
199 s.headerLocs = append(s.headerLocs, headerLoc{Offset: uint32(off), Len: uint32(n)})
200 off += 4 + n
201 }
202 s.headerAtOff = off
203 if off != size {
204 if err := s.headers.Truncate(off); err != nil {
205 return fmt.Errorf("headerstore: truncate headers: %w", err)
206 }
207 }
208 return nil
209 }
210
211 // loadFilters walks the filter record file and checks every record's header
212 // against its bytes as it goes, so a torn append at the end is the only thing
213 // that can be dropped and anything else is an error.
214 func (s *HeaderStore) loadFilters() error {
215 fi, err := s.filters.Stat()
216 if err != nil {
217 return err
218 }
219 size := fi.Size()
220 var off int64
221 for off+16 <= size {
222 var rec [16]byte
223 if _, err := s.filters.ReadAt(rec[:], off); err != nil {
224 break
225 }
226 length := int64(getUint32LE(rec[0:4]))
227 height := getUint32LE(rec[4:8])
228 var hash chainhash.Hash
229 copy(hash[:], rec[8:16])
230 if off+16+length > size {
231 break
232 }
233 buf := make([]byte, length)
234 if _, err := s.filters.ReadAt(buf, off+16); err != nil {
235 break
236 }
237 if chainhash.DoubleHashH(buf) != hash {
238 if off+16+length == size {
239 break
240 }
241 return fmt.Errorf("headerstore: filter at height %d does not commit to its hash", height)
242 }
243 s.filterLocs[height] = filterLoc{Offset: uint32(off), Len: uint32(length), Hash: hash}
244 if !s.hasFilters || height > s.filterTip {
245 s.filterTip = height
246 s.hasFilters = true
247 }
248 off += 16 + length
249 }
250 s.filtersAt = off
251 if off != size {
252 if err := s.filters.Truncate(off); err != nil {
253 return fmt.Errorf("headerstore: truncate filters: %w", err)
254 }
255 }
256 return nil
257 }
258
259 func recordCount(f *os.File, size int64) (uint32, error) {
260 fi, err := f.Stat()
261 if err != nil {
262 return 0, err
263 }
264 return uint32(fi.Size() / size), nil
265 }
266
267 // Anchor implements neutrino.Store.
268 func (s *HeaderStore) Anchor() (neutrino.Anchor, bool) {
269 s.mu.RLock()
270 defer s.mu.RUnlock()
271 return s.anchor, s.hasAnchor
272 }
273
274 // SetAnchor implements neutrino.Store. The anchor is written to disk before it
275 // is returned as set, so a crash cannot leave a store that claims a chain it
276 // does not start from.
277 func (s *HeaderStore) SetAnchor(a neutrino.Anchor) error {
278 s.mu.Lock()
279 defer s.mu.Unlock()
280 if s.hasAnchor {
281 return errors.New("headerstore: anchor already set")
282 }
283 if a.BlockHash == (chainhash.Hash{}) {
284 return errors.New("headerstore: anchor has no block hash")
285 }
286 if a.FilterHeight < -1 {
287 return errors.New("headerstore: anchor filter height below -1")
288 }
289 raw, err := anchorJSONFrom(a).encode()
290 if err != nil {
291 return err
292 }
293 if err := writeFileAtomic(filepath.Join(s.dir, anchorName), raw); err != nil {
294 return err
295 }
296 s.anchor = a
297 s.hasAnchor = true
298 return nil
299 }
300
301 // HeaderTip implements neutrino.Store.
302 func (s *HeaderStore) HeaderTip() (uint32, chainhash.Hash, bool) {
303 s.mu.RLock()
304 defer s.mu.RUnlock()
305 if !s.hasAnchor {
306 return 0, chainhash.Hash{}, false
307 }
308 if len(s.headerLocs) == 0 {
309 return s.anchor.Height, s.anchor.BlockHash, true
310 }
311 tip := s.anchor.Height + uint32(len(s.headerLocs)) - 1
312 h, ok := s.headerAtLocked(tip)
313 if !ok {
314 return 0, chainhash.Hash{}, false
315 }
316 return tip, h.BlockHash(), true
317 }
318
319 // Header implements neutrino.Store.
320 func (s *HeaderStore) Header(height uint32) (btcwire.BlockHeader, bool) {
321 s.mu.RLock()
322 defer s.mu.RUnlock()
323 return s.headerAtLocked(height)
324 }
325
326 func (s *HeaderStore) headerAtLocked(height uint32) (btcwire.BlockHeader, bool) {
327 // Records are contiguous from the anchor height, so the record at a height
328 // is the one at the offset from the anchor.
329 if !s.hasAnchor || height < s.anchor.Height {
330 return btcwire.BlockHeader{}, false
331 }
332 idx := height - s.anchor.Height
333 if int(idx) >= len(s.headerLocs) {
334 return btcwire.BlockHeader{}, false
335 }
336 l := s.headerLocs[idx]
337 buf := make([]byte, l.Len)
338 if _, err := s.headers.ReadAt(buf, int64(l.Offset)+4); err != nil {
339 return btcwire.BlockHeader{}, false
340 }
341 var h btcwire.BlockHeader
342 if err := h.DeserializeAny(buf); err != nil {
343 return btcwire.BlockHeader{}, false
344 }
345 return h, true
346 }
347
348 // PutHeaders implements neutrino.Store.
349 func (s *HeaderStore) PutHeaders(start uint32, headers []btcwire.BlockHeader) error {
350 s.mu.Lock()
351 defer s.mu.Unlock()
352 if !s.hasAnchor {
353 return errors.New("headerstore: no anchor")
354 }
355 // Records are contiguous from the anchor height. Neutrino seeds the genesis
356 // header at the anchor height when the profile has no checkpoint, and every
357 // other append follows the last record, so both paths land on the same rule:
358 // the next record is the anchor height plus the record count.
359 want := s.anchor.Height + uint32(len(s.headerLocs))
360 if len(s.headerLocs) > 0 && start <= s.anchor.Height {
361 return fmt.Errorf("headerstore: headers start at %d, want one past the anchor", start)
362 }
363 if start != want {
364 return fmt.Errorf("headerstore: headers start at %d, want %d", start, want)
365 }
366 // Each record is its own width, which is the header's: the fork's form is
367 // wider, and one chain holds both either side of its first v2 height.
368 var buf []byte
369 locs := make([]headerLoc, 0, len(headers))
370 off := s.headerAtOff
371 for i := range headers {
372 enc := headers[i].SerializeAll()
373 var pfx [4]byte
374 putUint32LE(pfx[:], uint32(len(enc)))
375 buf = append(buf, pfx[:]...)
376 locs = append(locs, headerLoc{Offset: uint32(off), Len: uint32(len(enc))})
377 off += 4 + int64(len(enc))
378 buf = append(buf, enc...)
379 }
380 if _, err := s.headers.WriteAt(buf, s.headerAtOff); err != nil {
381 return fmt.Errorf("headerstore: write headers: %w", err)
382 }
383 s.headerAtOff = off
384 s.headerLocs = append(s.headerLocs, locs...)
385 return nil
386 }
387
388 // FilterHeaderTip implements neutrino.Store.
389 //
390 // A store whose filters this instance built itself has no filter anchor: its
391 // records are dense from height 0, so the tip is the last record.
392 func (s *HeaderStore) FilterHeaderTip() (uint32, chainhash.Hash, bool) {
393 s.mu.RLock()
394 defer s.mu.RUnlock()
395 if !s.hasAnchor {
396 return 0, chainhash.Hash{}, false
397 }
398 if s.anchor.FilterHeight < 0 {
399 if s.fheaderCount == 0 {
400 return 0, chainhash.Hash{}, false
401 }
402 tip := s.fheaderCount - 1
403 h, ok := s.fheaderAtLocked(tip)
404 if !ok {
405 return 0, chainhash.Hash{}, false
406 }
407 return tip, h, true
408 }
409 anchorH := uint32(s.anchor.FilterHeight)
410 if s.fheaderCount == 0 {
411 return anchorH, s.anchor.FilterHeader, true
412 }
413 tip := anchorH + s.fheaderCount
414 h, ok := s.fheaderAtLocked(tip)
415 if !ok {
416 return 0, chainhash.Hash{}, false
417 }
418 return tip, h, true
419 }
420
421 // FilterHeader implements neutrino.Store. The anchor height's header is the
422 // anchor's; the records start at the next height.
423 func (s *HeaderStore) FilterHeader(height uint32) (chainhash.Hash, bool) {
424 s.mu.RLock()
425 defer s.mu.RUnlock()
426 if !s.hasAnchor {
427 return chainhash.Hash{}, false
428 }
429 if s.anchor.FilterHeight < 0 {
430 return s.fheaderAtLocked(height)
431 }
432 if height == uint32(s.anchor.FilterHeight) {
433 return s.anchor.FilterHeader, true
434 }
435 return s.fheaderAtLocked(height)
436 }
437
438 func (s *HeaderStore) fheaderAtLocked(height uint32) (chainhash.Hash, bool) {
439 if !s.hasAnchor {
440 return chainhash.Hash{}, false
441 }
442 if s.anchor.FilterHeight < 0 {
443 // Dense: record i is height i.
444 if height >= s.fheaderCount {
445 return chainhash.Hash{}, false
446 }
447 var h chainhash.Hash
448 if _, err := s.fheaders.ReadAt(h[:], int64(height)*chainhash.HashSize); err != nil {
449 return chainhash.Hash{}, false
450 }
451 return h, true
452 }
453 anchorH := uint32(s.anchor.FilterHeight)
454 if height <= anchorH || height-anchorH > s.fheaderCount {
455 return chainhash.Hash{}, false
456 }
457 var h chainhash.Hash
458 if _, err := s.fheaders.ReadAt(h[:], int64(height-anchorH-1)*chainhash.HashSize); err != nil {
459 return chainhash.Hash{}, false
460 }
461 return h, true
462 }
463
464 // FilterHash implements neutrino.Store.
465 func (s *HeaderStore) FilterHash(height uint32) (chainhash.Hash, bool) {
466 s.mu.RLock()
467 defer s.mu.RUnlock()
468 if !s.hasAnchor {
469 return chainhash.Hash{}, false
470 }
471 if s.anchor.FilterHeight < 0 {
472 // Dense: record i is height i.
473 if height >= s.fhashCount {
474 return chainhash.Hash{}, false
475 }
476 var h chainhash.Hash
477 if _, err := s.fhashes.ReadAt(h[:], int64(height)*chainhash.HashSize); err != nil {
478 return chainhash.Hash{}, false
479 }
480 return h, true
481 }
482 anchorH := uint32(s.anchor.FilterHeight)
483 if height <= anchorH || height-anchorH-1 >= s.fhashCount {
484 return chainhash.Hash{}, false
485 }
486 var h chainhash.Hash
487 if _, err := s.fhashes.ReadAt(h[:], int64(height-anchorH-1)*chainhash.HashSize); err != nil {
488 return chainhash.Hash{}, false
489 }
490 return h, true
491 }
492
493 // PutFilterHeaders implements neutrino.Store. The two slices are parallel; the
494 // caller has already verified the fold.
495 func (s *HeaderStore) PutFilterHeaders(start uint32, filterHashes, filterHeaders []chainhash.Hash) error {
496 s.mu.Lock()
497 defer s.mu.Unlock()
498 if !s.hasAnchor || s.anchor.FilterHeight < 0 {
499 return errors.New("headerstore: no filter header anchor")
500 }
501 if len(filterHashes) != len(filterHeaders) {
502 return errors.New("headerstore: filter hashes and headers differ in length")
503 }
504 // The anchor height's filter header is not a record, so the first record is
505 // at the anchor height plus one.
506 anchorH := uint32(s.anchor.FilterHeight)
507 want := anchorH + 1 + s.fhashCount
508 if start != want {
509 return fmt.Errorf("headerstore: filter headers start at %d, want %d", start, want)
510 }
511 fh := make([]byte, 0, len(filterHashes)*chainhash.HashSize)
512 for _, h := range filterHashes {
513 fh = append(fh, h[:]...)
514 }
515 if _, err := s.fhashes.WriteAt(fh, int64(s.fhashCount)*chainhash.HashSize); err != nil {
516 return fmt.Errorf("headerstore: write filter hashes: %w", err)
517 }
518 hh := make([]byte, 0, len(filterHeaders)*chainhash.HashSize)
519 for _, h := range filterHeaders {
520 hh = append(hh, h[:]...)
521 }
522 if _, err := s.fheaders.WriteAt(hh, int64(s.fheaderCount)*chainhash.HashSize); err != nil {
523 return fmt.Errorf("headerstore: write filter headers: %w", err)
524 }
525 s.fhashCount += uint32(len(filterHashes))
526 s.fheaderCount += uint32(len(filterHeaders))
527 return nil
528 }
529
530 // PutFilterHeaderRecord appends the filter hash and its folded header at a
531 // height, for a chain whose filters this instance builds itself.
532 //
533 // A store has one mode. Neutrino's PutFilterHeaders writes records from the
534 // anchor's filter height plus one, because its fold starts from a filter header
535 // the anchor names; a self-built fold starts at height 0 with a zero previous
536 // header, so its records are dense from 0 and there is no filter anchor. A
537 // store that has one cannot take the other, and says so rather than writing a
538 // file two readers would interpret differently.
539 func (s *HeaderStore) PutFilterHeaderRecord(height uint32, filterHash, filterHeader chainhash.Hash) error {
540 s.mu.Lock()
541 defer s.mu.Unlock()
542 if !s.hasAnchor {
543 return errors.New("headerstore: no anchor")
544 }
545 if s.anchor.FilterHeight >= 0 {
546 return fmt.Errorf("headerstore: filter headers come from the anchor at %d; a built fold cannot append to them", s.anchor.FilterHeight)
547 }
548 if height != s.fhashCount {
549 return fmt.Errorf("headerstore: filter header at %d, want %d", height, s.fhashCount)
550 }
551 if _, err := s.fhashes.WriteAt(filterHash[:], int64(s.fhashCount)*chainhash.HashSize); err != nil {
552 return fmt.Errorf("headerstore: write filter hash: %w", err)
553 }
554 if _, err := s.fheaders.WriteAt(filterHeader[:], int64(s.fheaderCount)*chainhash.HashSize); err != nil {
555 return fmt.Errorf("headerstore: write filter header: %w", err)
556 }
557 s.fhashCount++
558 s.fheaderCount++
559 return nil
560 }
561
562 // FilterTip implements neutrino.Store.
563 func (s *HeaderStore) FilterTip() (uint32, bool) {
564 s.mu.RLock()
565 defer s.mu.RUnlock()
566 return s.filterTip, s.hasFilters
567 }
568
569 // Filter implements neutrino.Store.
570 func (s *HeaderStore) Filter(height uint32) ([]byte, bool) {
571 s.mu.RLock()
572 loc, ok := s.filterLocs[height]
573 s.mu.RUnlock()
574 if !ok {
575 return nil, false
576 }
577 buf := make([]byte, loc.Len)
578 if _, err := s.filters.ReadAt(buf, int64(loc.Offset)+16); err != nil {
579 return nil, false
580 }
581 return buf, true
582 }
583
584 // PutFilter implements neutrino.Store. The bytes are hashed and compared with
585 // the hash the caller says the header chain commits to, so a filter that does
586 // not verify cannot enter the store through this door either.
587 func (s *HeaderStore) PutFilter(height uint32, blockHash, filterHash chainhash.Hash, filter []byte) error {
588 if got := chainhash.DoubleHashH(filter); got != filterHash {
589 return fmt.Errorf("headerstore: filter at %d hashes to %s, not %s", height, got, filterHash)
590 }
591 s.mu.Lock()
592 defer s.mu.Unlock()
593 if _, ok := s.filterLocs[height]; ok {
594 return nil
595 }
596 var rec [16]byte
597 putUint32LE(rec[0:4], uint32(len(filter)))
598 putUint32LE(rec[4:8], height)
599 copy(rec[8:16], filterHash[:])
600 off := s.filtersAt
601 if _, err := s.filters.WriteAt(rec[:], off); err != nil {
602 return fmt.Errorf("headerstore: write filter record: %w", err)
603 }
604 if _, err := s.filters.WriteAt(filter, off+16); err != nil {
605 return fmt.Errorf("headerstore: write filter: %w", err)
606 }
607 s.filtersAt = off + 16 + int64(len(filter))
608 s.filterLocs[height] = filterLoc{Offset: uint32(off), Len: uint32(len(filter)), Hash: filterHash}
609 if !s.hasFilters || height > s.filterTip {
610 s.filterTip = height
611 s.hasFilters = true
612 }
613 _ = blockHash
614 return nil
615 }
616
617 // Truncate implements neutrino.Store: it drops every header, filter header,
618 // filter hash and filter at or above from.
619 func (s *HeaderStore) Truncate(from uint32) error {
620 s.mu.Lock()
621 defer s.mu.Unlock()
622 if !s.hasAnchor {
623 return errors.New("headerstore: no anchor")
624 }
625 if from <= s.anchor.Height {
626 return fmt.Errorf("headerstore: truncate at %d is at or below the anchor", from)
627 }
628 // Records are contiguous from the anchor height, so from keeps the records
629 // for the heights below it.
630 {
631 keep := uint32(from - s.anchor.Height)
632 if int(keep) < len(s.headerLocs) {
633 cut := int64(s.headerLocs[keep].Offset)
634 if err := s.headers.Truncate(cut); err != nil {
635 return fmt.Errorf("headerstore: truncate headers: %w", err)
636 }
637 s.headerLocs = s.headerLocs[:keep]
638 s.headerAtOff = cut
639 }
640 }
641 if s.anchor.FilterHeight < 0 {
642 // Dense records: from keeps the records for heights below it, and
643 // there is no anchor record to preserve.
644 keep := int64(from) * chainhash.HashSize
645 if keep < int64(s.fhashCount)*chainhash.HashSize {
646 if err := s.fhashes.Truncate(keep); err != nil {
647 return fmt.Errorf("headerstore: truncate filter hashes: %w", err)
648 }
649 if err := s.fheaders.Truncate(keep); err != nil {
650 return fmt.Errorf("headerstore: truncate filter headers: %w", err)
651 }
652 s.fhashCount = uint32(keep / chainhash.HashSize)
653 s.fheaderCount = s.fhashCount
654 }
655 }
656 if s.anchor.FilterHeight >= 0 {
657 // Filter header records start at the anchor height plus one, so from
658 // keeps the records for heights below it.
659 var keepRecords int64
660 if from > uint32(s.anchor.FilterHeight)+1 {
661 keepRecords = int64(from-uint32(s.anchor.FilterHeight)-1) * chainhash.HashSize
662 }
663 if keepRecords < int64(s.fhashCount)*chainhash.HashSize {
664 if err := s.fhashes.Truncate(keepRecords); err != nil {
665 return fmt.Errorf("headerstore: truncate filter hashes: %w", err)
666 }
667 if err := s.fheaders.Truncate(keepRecords); err != nil {
668 return fmt.Errorf("headerstore: truncate filter headers: %w", err)
669 }
670 s.fhashCount = uint32(keepRecords / chainhash.HashSize)
671 s.fheaderCount = s.fhashCount
672 }
673 }
674 // Filters at or above from go, and since they are appended in height order
675 // the file can be cut at the first one dropped.
676 var first int64 = -1
677 for h, loc := range s.filterLocs {
678 if h >= from && (first < 0 || int64(loc.Offset) < first) {
679 first = int64(loc.Offset)
680 }
681 }
682 if first >= 0 {
683 if err := s.filters.Truncate(first); err != nil {
684 return fmt.Errorf("headerstore: truncate filters: %w", err)
685 }
686 s.filtersAt = first
687 }
688 for h := range s.filterLocs {
689 if h >= from {
690 delete(s.filterLocs, h)
691 }
692 }
693 s.hasFilters = false
694 s.filterTip = 0
695 for h := range s.filterLocs {
696 if !s.hasFilters || h > s.filterTip {
697 s.filterTip = h
698 s.hasFilters = true
699 }
700 }
701 return nil
702 }
703
704 // Close closes the files.
705 func (s *HeaderStore) Close() error {
706 s.mu.Lock()
707 defer s.mu.Unlock()
708 var errs []error
709 for _, f := range []*os.File{s.headers, s.fheaders, s.fhashes, s.filters} {
710 if f == nil {
711 continue
712 }
713 if err := f.Sync(); err != nil {
714 errs = append(errs, err)
715 }
716 if err := f.Close(); err != nil {
717 errs = append(errs, err)
718 }
719 }
720 return errors.Join(errs...)
721 }
722
723 // anchorJSON is the on-disk anchor.
724 type anchorJSON struct {
725 Height uint32 `json:"height"`
726 BlockHash string `json:"block_hash"`
727 FilterHeight int32 `json:"filter_height"`
728 FilterHeader string `json:"filter_header"`
729 }
730
731 func anchorJSONFrom(a neutrino.Anchor) anchorJSON {
732 return anchorJSON{
733 Height: a.Height,
734 BlockHash: a.BlockHash.String(),
735 FilterHeight: a.FilterHeight,
736 FilterHeader: a.FilterHeader.String(),
737 }
738 }
739
740 func (a anchorJSON) encode() ([]byte, error) {
741 return jsonMarshal(a)
742 }
743
744 func (a *anchorJSON) decode(raw []byte) error {
745 return jsonUnmarshal(raw, a)
746 }
747
748 func (a anchorJSON) toAnchor() (neutrino.Anchor, error) {
749 bh, err := chainhash.NewHashFromStr(a.BlockHash)
750 if err != nil {
751 return neutrino.Anchor{}, fmt.Errorf("headerstore: anchor block hash: %w", err)
752 }
753 var fh chainhash.Hash
754 if a.FilterHeight >= 0 {
755 f, err := chainhash.NewHashFromStr(a.FilterHeader)
756 if err != nil {
757 return neutrino.Anchor{}, fmt.Errorf("headerstore: anchor filter header: %w", err)
758 }
759 fh = *f
760 }
761 return neutrino.Anchor{Height: a.Height, BlockHash: *bh, FilterHeight: a.FilterHeight, FilterHeader: fh}, nil
762 }
763