// Package staging is the append log a fill writes to before anything has // verified a byte of it. // // Bytes arriving from a peer are untrusted. They become a stored block only // when a separate pass has hashed them against the chain's header at their // height, so the download writes them here and nothing else: no hash check, no // index, no filter, no UTXO work inside the network loop. Nothing that serves // data reads this directory. Only internal/process does, and it moves a body // into the body store or drops it. // // Layout, one directory per chain because a claim's height is a height on one // chain: // // .dat [u32 len][bytes] per body, in append order // claims.dat [u32 seg][u32 height][u32 len][32 hash] per body // // A claim carries the height and hash the downloader asked for, so the // processing pass does not re-derive either. The record's position in its // segment is the running sum of the lengths claimed before it in that segment, // which holds because one append writes the bytes and the claim together. package staging import ( "errors" "fmt" "os" "path/filepath" "sort" "sync" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // maxSegBytes is where a new segment is started. A body appended past it is // stored whole, so the ceiling is soft by one body. const maxSegBytes = 512 * 1024 * 1024 // claimSize is seg (4), height (4), length (4), hash (32). const claimSize = 44 // claimsName is the claim file inside a staging directory. const claimsName = "claims.dat" // Claim is one body's identity as the downloader asked for it. type Claim struct { Seg uint32 Height uint32 Len uint32 Hash chainhash.Hash } // Log is one chain's staging directory. It is safe for concurrent use: the // fill's lanes append from several goroutines and one lock covers the bytes and // the claim that describes them. type Log struct { dir string mu sync.Mutex claims []Claim heights map[uint32]bool segEnd map[uint32]int64 segFile map[uint32]*os.File // claimFile stays open: one append syscall per body is the whole point of // the log, and an open and a close around it would be three. claimFile *os.File writeSeg uint32 closed bool // bytes is the total length of every body the log holds. bytes int64 } // Open reads a staging directory, keeping every claim whose body is complete // and cutting back a torn append at the end. func Open(dir string) (*Log, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("staging: create %s: %w", dir, err) } l := &Log{dir: dir, heights: map[uint32]bool{}, segEnd: map[uint32]int64{}, segFile: map[uint32]*os.File{}} if err := l.load(); err != nil { return nil, err } return l, nil } // Dir is the directory a chain's staging log lives in. func Dir(data, chainName string) string { return filepath.Join(data, "blocks", "staging", chainName) } func (l *Log) load() error { raw, err := os.ReadFile(filepath.Join(l.dir, claimsName)) if err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("staging: read claims: %w", err) } good := 0 for off := 0; off+claimSize <= len(raw); off += claimSize { c := decodeClaim(raw[off : off+claimSize]) // The body must be complete in its segment: the claim is durable only // after the bytes it describes. end := l.segEnd[c.Seg] + 4 + int64(c.Len) if fi, err := os.Stat(l.segPath(c.Seg)); err != nil || fi.Size() < end { break } l.segEnd[c.Seg] = end l.claims = append(l.claims, c) l.heights[c.Height] = true l.bytes += int64(c.Len) good += claimSize } if good != len(raw) { if err := os.Truncate(filepath.Join(l.dir, claimsName), int64(good)); err != nil { return fmt.Errorf("staging: truncate claims: %w", err) } // And every segment back to the last body the surviving claims name. for seg, end := range l.segEnd { if fi, err := os.Stat(l.segPath(seg)); err == nil && fi.Size() > end { if err := os.Truncate(l.segPath(seg), end); err != nil { return fmt.Errorf("staging: truncate segment %d: %w", seg, err) } } } } // Any segment file the claims do not reach is from an append whose claim // never landed: it holds nothing anything can name, so it goes. segs, err := l.segments() if err != nil { return err } for _, seg := range segs { if _, ok := l.segEnd[seg]; ok { continue } if err := os.Remove(l.segPath(seg)); err != nil { return fmt.Errorf("staging: remove %s: %w", l.segPath(seg), err) } } l.writeSeg = 0 if len(l.claims) > 0 { l.writeSeg = l.claims[len(l.claims)-1].Seg } cf, err := os.OpenFile(filepath.Join(l.dir, claimsName), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { return fmt.Errorf("staging: open claims: %w", err) } l.claimFile = cf return nil } // segments lists the segment files present, ascending. func (l *Log) segments() ([]uint32, error) { entries, err := os.ReadDir(l.dir) if err != nil { return nil, err } var out []uint32 for _, e := range entries { name := e.Name() if filepath.Ext(name) != ".dat" || name == claimsName { continue } var seg uint32 if _, err := fmt.Sscanf(name, "%d.dat", &seg); err != nil { continue } out = append(out, seg) } sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) return out, nil } func (l *Log) segPath(seg uint32) string { return filepath.Join(l.dir, fmt.Sprintf("%08d.dat", seg)) } // Append writes one body and its claim. The bytes go first: a claim is durable // only when the body it names is. func (l *Log) Append(height uint32, hash chainhash.Hash, raw []byte) error { l.mu.Lock() defer l.mu.Unlock() if l.closed { return errors.New("staging: log is closed") } if l.segEnd[l.writeSeg] >= maxSegBytes { l.writeSeg++ } f, err := l.file(l.writeSeg) if err != nil { return err } var pfx [4]byte putUint32LE(pfx[:], uint32(len(raw))) if _, err := f.Write(pfx[:]); err != nil { return fmt.Errorf("staging: write: %w", err) } if _, err := f.Write(raw); err != nil { return fmt.Errorf("staging: write: %w", err) } l.segEnd[l.writeSeg] += 4 + int64(len(raw)) c := Claim{Seg: l.writeSeg, Height: height, Len: uint32(len(raw)), Hash: hash} rec := encodeClaim(c) if _, err := l.claimFile.Write(rec[:]); err != nil { return fmt.Errorf("staging: write claim: %w", err) } l.claims = append(l.claims, c) l.heights[height] = true l.bytes += int64(len(raw)) return nil } // file returns the open handle for a segment, opening it on first use. func (l *Log) file(seg uint32) (*os.File, error) { if f, ok := l.segFile[seg]; ok { return f, nil } f, err := os.OpenFile(l.segPath(seg), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { return nil, fmt.Errorf("staging: open %s: %w", l.segPath(seg), err) } l.segFile[seg] = f return f, nil } // Walk reads every claim and its body, in claim order. A body that cannot be // read stops the walk with the claim's height in the error: the pass is // idempotent per body, so the caller reruns it rather than skipping. func (l *Log) Walk(fn func(Claim, []byte) error) error { l.mu.Lock() claims := append([]Claim(nil), l.claims...) l.mu.Unlock() readers := map[uint32]*os.File{} defer func() { for _, f := range readers { f.Close() } }() // offs is the read position in each segment, in claim order. offs := map[uint32]int64{} for _, c := range claims { f, ok := readers[c.Seg] if !ok { var err error f, err = os.Open(l.segPath(c.Seg)) if err != nil { return fmt.Errorf("staging: open segment %d: %w", c.Seg, err) } readers[c.Seg] = f } off := offs[c.Seg] buf := make([]byte, c.Len) if _, err := f.ReadAt(buf, off+4); err != nil { return fmt.Errorf("staging: body at height %d: %w", c.Height, err) } offs[c.Seg] = off + 4 + int64(c.Len) if err := fn(c, buf); err != nil { return err } } return nil } // Has reports whether the log already holds a body for a height, which is what // a resumed fill asks so it does not download it twice. func (l *Log) Has(height uint32) bool { l.mu.Lock() defer l.mu.Unlock() return l.heights[height] } // Len is the number of bodies the log holds. func (l *Log) Len() int { l.mu.Lock() defer l.mu.Unlock() return len(l.claims) } // Bytes is the total size of the bodies the log holds. func (l *Log) Bytes() int64 { l.mu.Lock() defer l.mu.Unlock() return l.bytes } // Drain removes every body and claim. It is what the processing pass calls once // it has moved or dropped them all: the log says nothing about what was stored, // so there is nothing in it to keep. func (l *Log) Drain() error { l.mu.Lock() defer l.mu.Unlock() if err := l.closeFiles(); err != nil { return err } segs, err := l.segments() if err != nil { return err } for _, seg := range segs { if err := os.Remove(l.segPath(seg)); err != nil { return fmt.Errorf("staging: remove %s: %w", l.segPath(seg), err) } } if err := os.Remove(filepath.Join(l.dir, claimsName)); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("staging: remove claims: %w", err) } l.claims = nil l.heights = map[uint32]bool{} l.segEnd = map[uint32]int64{} l.writeSeg = 0 l.bytes = 0 return nil } // Close flushes and closes the segment files. func (l *Log) Close() error { l.mu.Lock() defer l.mu.Unlock() l.closed = true return l.closeFiles() } func (l *Log) closeFiles() error { var errs []error if l.claimFile != nil { if err := l.claimFile.Sync(); err != nil { errs = append(errs, err) } if err := l.claimFile.Close(); err != nil { errs = append(errs, err) } l.claimFile = nil } for seg, f := range l.segFile { if err := f.Sync(); err != nil { errs = append(errs, err) } if err := f.Close(); err != nil { errs = append(errs, err) } delete(l.segFile, seg) } return errors.Join(errs...) } func encodeClaim(c Claim) [claimSize]byte { var rec [claimSize]byte putUint32LE(rec[0:4], c.Seg) putUint32LE(rec[4:8], c.Height) putUint32LE(rec[8:12], c.Len) copy(rec[12:], c.Hash[:]) return rec } func decodeClaim(raw []byte) Claim { var c Claim c.Seg = getUint32LE(raw[0:4]) c.Height = getUint32LE(raw[4:8]) c.Len = getUint32LE(raw[8:12]) copy(c.Hash[:], raw[12:claimSize]) return c } 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 }