1 // Package staging is the append log a fill writes to before anything has
2 // verified a byte of it.
3 //
4 // Bytes arriving from a peer are untrusted. They become a stored block only
5 // when a separate pass has hashed them against the chain's header at their
6 // height, so the download writes them here and nothing else: no hash check, no
7 // index, no filter, no UTXO work inside the network loop. Nothing that serves
8 // data reads this directory. Only internal/process does, and it moves a body
9 // into the body store or drops it.
10 //
11 // Layout, one directory per chain because a claim's height is a height on one
12 // chain:
13 //
14 // <seg>.dat [u32 len][bytes] per body, in append order
15 // claims.dat [u32 seg][u32 height][u32 len][32 hash] per body
16 //
17 // A claim carries the height and hash the downloader asked for, so the
18 // processing pass does not re-derive either. The record's position in its
19 // segment is the running sum of the lengths claimed before it in that segment,
20 // which holds because one append writes the bytes and the claim together.
21 package staging
22 23 import (
24 "errors"
25 "fmt"
26 "os"
27 "path/filepath"
28 "sort"
29 "sync"
30 31 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
32 )
33 34 // maxSegBytes is where a new segment is started. A body appended past it is
35 // stored whole, so the ceiling is soft by one body.
36 const maxSegBytes = 512 * 1024 * 1024
37 38 // claimSize is seg (4), height (4), length (4), hash (32).
39 const claimSize = 44
40 41 // claimsName is the claim file inside a staging directory.
42 const claimsName = "claims.dat"
43 44 // Claim is one body's identity as the downloader asked for it.
45 type Claim struct {
46 Seg uint32
47 Height uint32
48 Len uint32
49 Hash chainhash.Hash
50 }
51 52 // Log is one chain's staging directory. It is safe for concurrent use: the
53 // fill's lanes append from several goroutines and one lock covers the bytes and
54 // the claim that describes them.
55 type Log struct {
56 dir string
57 58 mu sync.Mutex
59 claims []Claim
60 heights map[uint32]bool
61 segEnd map[uint32]int64
62 segFile map[uint32]*os.File
63 // claimFile stays open: one append syscall per body is the whole point of
64 // the log, and an open and a close around it would be three.
65 claimFile *os.File
66 writeSeg uint32
67 closed bool
68 // bytes is the total length of every body the log holds.
69 bytes int64
70 }
71 72 // Open reads a staging directory, keeping every claim whose body is complete
73 // and cutting back a torn append at the end.
74 func Open(dir string) (*Log, error) {
75 if err := os.MkdirAll(dir, 0o755); err != nil {
76 return nil, fmt.Errorf("staging: create %s: %w", dir, err)
77 }
78 l := &Log{dir: dir, heights: map[uint32]bool{}, segEnd: map[uint32]int64{}, segFile: map[uint32]*os.File{}}
79 if err := l.load(); err != nil {
80 return nil, err
81 }
82 return l, nil
83 }
84 85 // Dir is the directory a chain's staging log lives in.
86 func Dir(data, chainName string) string {
87 return filepath.Join(data, "blocks", "staging", chainName)
88 }
89 90 func (l *Log) load() error {
91 raw, err := os.ReadFile(filepath.Join(l.dir, claimsName))
92 if err != nil && !errors.Is(err, os.ErrNotExist) {
93 return fmt.Errorf("staging: read claims: %w", err)
94 }
95 good := 0
96 for off := 0; off+claimSize <= len(raw); off += claimSize {
97 c := decodeClaim(raw[off : off+claimSize])
98 // The body must be complete in its segment: the claim is durable only
99 // after the bytes it describes.
100 end := l.segEnd[c.Seg] + 4 + int64(c.Len)
101 if fi, err := os.Stat(l.segPath(c.Seg)); err != nil || fi.Size() < end {
102 break
103 }
104 l.segEnd[c.Seg] = end
105 l.claims = append(l.claims, c)
106 l.heights[c.Height] = true
107 l.bytes += int64(c.Len)
108 good += claimSize
109 }
110 if good != len(raw) {
111 if err := os.Truncate(filepath.Join(l.dir, claimsName), int64(good)); err != nil {
112 return fmt.Errorf("staging: truncate claims: %w", err)
113 }
114 // And every segment back to the last body the surviving claims name.
115 for seg, end := range l.segEnd {
116 if fi, err := os.Stat(l.segPath(seg)); err == nil && fi.Size() > end {
117 if err := os.Truncate(l.segPath(seg), end); err != nil {
118 return fmt.Errorf("staging: truncate segment %d: %w", seg, err)
119 }
120 }
121 }
122 }
123 // Any segment file the claims do not reach is from an append whose claim
124 // never landed: it holds nothing anything can name, so it goes.
125 segs, err := l.segments()
126 if err != nil {
127 return err
128 }
129 for _, seg := range segs {
130 if _, ok := l.segEnd[seg]; ok {
131 continue
132 }
133 if err := os.Remove(l.segPath(seg)); err != nil {
134 return fmt.Errorf("staging: remove %s: %w", l.segPath(seg), err)
135 }
136 }
137 l.writeSeg = 0
138 if len(l.claims) > 0 {
139 l.writeSeg = l.claims[len(l.claims)-1].Seg
140 }
141 cf, err := os.OpenFile(filepath.Join(l.dir, claimsName), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
142 if err != nil {
143 return fmt.Errorf("staging: open claims: %w", err)
144 }
145 l.claimFile = cf
146 return nil
147 }
148 149 // segments lists the segment files present, ascending.
150 func (l *Log) segments() ([]uint32, error) {
151 entries, err := os.ReadDir(l.dir)
152 if err != nil {
153 return nil, err
154 }
155 var out []uint32
156 for _, e := range entries {
157 name := e.Name()
158 if filepath.Ext(name) != ".dat" || name == claimsName {
159 continue
160 }
161 var seg uint32
162 if _, err := fmt.Sscanf(name, "%d.dat", &seg); err != nil {
163 continue
164 }
165 out = append(out, seg)
166 }
167 sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
168 return out, nil
169 }
170 171 func (l *Log) segPath(seg uint32) string {
172 return filepath.Join(l.dir, fmt.Sprintf("%08d.dat", seg))
173 }
174 175 // Append writes one body and its claim. The bytes go first: a claim is durable
176 // only when the body it names is.
177 func (l *Log) Append(height uint32, hash chainhash.Hash, raw []byte) error {
178 l.mu.Lock()
179 defer l.mu.Unlock()
180 if l.closed {
181 return errors.New("staging: log is closed")
182 }
183 if l.segEnd[l.writeSeg] >= maxSegBytes {
184 l.writeSeg++
185 }
186 f, err := l.file(l.writeSeg)
187 if err != nil {
188 return err
189 }
190 var pfx [4]byte
191 putUint32LE(pfx[:], uint32(len(raw)))
192 if _, err := f.Write(pfx[:]); err != nil {
193 return fmt.Errorf("staging: write: %w", err)
194 }
195 if _, err := f.Write(raw); err != nil {
196 return fmt.Errorf("staging: write: %w", err)
197 }
198 l.segEnd[l.writeSeg] += 4 + int64(len(raw))
199 c := Claim{Seg: l.writeSeg, Height: height, Len: uint32(len(raw)), Hash: hash}
200 rec := encodeClaim(c)
201 if _, err := l.claimFile.Write(rec[:]); err != nil {
202 return fmt.Errorf("staging: write claim: %w", err)
203 }
204 l.claims = append(l.claims, c)
205 l.heights[height] = true
206 l.bytes += int64(len(raw))
207 return nil
208 }
209 210 // file returns the open handle for a segment, opening it on first use.
211 func (l *Log) file(seg uint32) (*os.File, error) {
212 if f, ok := l.segFile[seg]; ok {
213 return f, nil
214 }
215 f, err := os.OpenFile(l.segPath(seg), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
216 if err != nil {
217 return nil, fmt.Errorf("staging: open %s: %w", l.segPath(seg), err)
218 }
219 l.segFile[seg] = f
220 return f, nil
221 }
222 223 // Walk reads every claim and its body, in claim order. A body that cannot be
224 // read stops the walk with the claim's height in the error: the pass is
225 // idempotent per body, so the caller reruns it rather than skipping.
226 func (l *Log) Walk(fn func(Claim, []byte) error) error {
227 l.mu.Lock()
228 claims := append([]Claim(nil), l.claims...)
229 l.mu.Unlock()
230 readers := map[uint32]*os.File{}
231 defer func() {
232 for _, f := range readers {
233 f.Close()
234 }
235 }()
236 // offs is the read position in each segment, in claim order.
237 offs := map[uint32]int64{}
238 for _, c := range claims {
239 f, ok := readers[c.Seg]
240 if !ok {
241 var err error
242 f, err = os.Open(l.segPath(c.Seg))
243 if err != nil {
244 return fmt.Errorf("staging: open segment %d: %w", c.Seg, err)
245 }
246 readers[c.Seg] = f
247 }
248 off := offs[c.Seg]
249 buf := make([]byte, c.Len)
250 if _, err := f.ReadAt(buf, off+4); err != nil {
251 return fmt.Errorf("staging: body at height %d: %w", c.Height, err)
252 }
253 offs[c.Seg] = off + 4 + int64(c.Len)
254 if err := fn(c, buf); err != nil {
255 return err
256 }
257 }
258 return nil
259 }
260 261 // Has reports whether the log already holds a body for a height, which is what
262 // a resumed fill asks so it does not download it twice.
263 func (l *Log) Has(height uint32) bool {
264 l.mu.Lock()
265 defer l.mu.Unlock()
266 return l.heights[height]
267 }
268 269 // Len is the number of bodies the log holds.
270 func (l *Log) Len() int {
271 l.mu.Lock()
272 defer l.mu.Unlock()
273 return len(l.claims)
274 }
275 276 // Bytes is the total size of the bodies the log holds.
277 func (l *Log) Bytes() int64 {
278 l.mu.Lock()
279 defer l.mu.Unlock()
280 return l.bytes
281 }
282 283 // Drain removes every body and claim. It is what the processing pass calls once
284 // it has moved or dropped them all: the log says nothing about what was stored,
285 // so there is nothing in it to keep.
286 func (l *Log) Drain() error {
287 l.mu.Lock()
288 defer l.mu.Unlock()
289 if err := l.closeFiles(); err != nil {
290 return err
291 }
292 segs, err := l.segments()
293 if err != nil {
294 return err
295 }
296 for _, seg := range segs {
297 if err := os.Remove(l.segPath(seg)); err != nil {
298 return fmt.Errorf("staging: remove %s: %w", l.segPath(seg), err)
299 }
300 }
301 if err := os.Remove(filepath.Join(l.dir, claimsName)); err != nil && !errors.Is(err, os.ErrNotExist) {
302 return fmt.Errorf("staging: remove claims: %w", err)
303 }
304 l.claims = nil
305 l.heights = map[uint32]bool{}
306 l.segEnd = map[uint32]int64{}
307 l.writeSeg = 0
308 l.bytes = 0
309 return nil
310 }
311 312 // Close flushes and closes the segment files.
313 func (l *Log) Close() error {
314 l.mu.Lock()
315 defer l.mu.Unlock()
316 l.closed = true
317 return l.closeFiles()
318 }
319 320 func (l *Log) closeFiles() error {
321 var errs []error
322 if l.claimFile != nil {
323 if err := l.claimFile.Sync(); err != nil {
324 errs = append(errs, err)
325 }
326 if err := l.claimFile.Close(); err != nil {
327 errs = append(errs, err)
328 }
329 l.claimFile = nil
330 }
331 for seg, f := range l.segFile {
332 if err := f.Sync(); err != nil {
333 errs = append(errs, err)
334 }
335 if err := f.Close(); err != nil {
336 errs = append(errs, err)
337 }
338 delete(l.segFile, seg)
339 }
340 return errors.Join(errs...)
341 }
342 343 func encodeClaim(c Claim) [claimSize]byte {
344 var rec [claimSize]byte
345 putUint32LE(rec[0:4], c.Seg)
346 putUint32LE(rec[4:8], c.Height)
347 putUint32LE(rec[8:12], c.Len)
348 copy(rec[12:], c.Hash[:])
349 return rec
350 }
351 352 func decodeClaim(raw []byte) Claim {
353 var c Claim
354 c.Seg = getUint32LE(raw[0:4])
355 c.Height = getUint32LE(raw[4:8])
356 c.Len = getUint32LE(raw[8:12])
357 copy(c.Hash[:], raw[12:claimSize])
358 return c
359 }
360 361 func putUint32LE(b []byte, v uint32) {
362 b[0] = byte(v)
363 b[1] = byte(v >> 8)
364 b[2] = byte(v >> 16)
365 b[3] = byte(v >> 24)
366 }
367 368 func getUint32LE(b []byte) uint32 {
369 return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
370 }
371