1 // Package utxostore holds a canonical UTXO set at a height, in files, and the
2 // checkpoints cut from it.
3 //
4 // The on-disk form is the plan's: a set is a sequence of sorted chunks of
5 // fixed-width entries, each readable and mergeable on its own, so applying a
6 // range's diff to it is a sequential merge rather than a load into memory.
7 // A checkpoint is a diff against the last checkpoint at or below its height,
8 // and the chain of those diffs from the genesis base is what a client applies
9 // to reach any checkpoint height.
10 //
11 // Nothing here is verified by trust: a checkpoint carries the name of the set
12 // it describes, and a client that applies the diffs recomputes that name from
13 // the result. A wrong diff gives a different name, and the client says so.
14 package utxostore
15 16 import (
17 "bufio"
18 "bytes"
19 "crypto/sha256"
20 "errors"
21 "fmt"
22 "io"
23 "os"
24 "path/filepath"
25 "sort"
26 "strconv"
27 "strings"
28 29 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
30 31 "git.smesh.lol/btcd-lite/internal/utxo"
32 )
33 34 // EntrySize is the encoded width of an entry.
35 const EntrySize = utxo.EntryEncodeSize
36 37 // SetFile is the name a canonical set is written under at a height.
38 func SetFile(height uint32) string { return fmt.Sprintf("set-%09d.dat", height) }
39 40 // IndexFile records every snapshot's height and name in a directory.
41 //
42 // A manifest needs the name of every snapshot, and the name is the double
43 // SHA-256 of the file, so naming them by reading them back means reading the
44 // whole dataset to answer one request. The writer knows each name as it writes
45 // it, so it records it here and a reader reads one small file.
46 const IndexFile = "index"
47 48 // indexLine is one record: the height in decimal, a space, the name in hex.
49 func indexLine(height uint32, name chainhash.Hash) []byte {
50 return []byte(fmt.Sprintf("%d %s\n", height, name))
51 }
52 53 // Names reads a directory's snapshot index: height to set name.
54 func Names(dir string) (map[uint32]chainhash.Hash, error) {
55 raw, err := os.ReadFile(filepath.Join(dir, IndexFile))
56 if err != nil {
57 return nil, fmt.Errorf("utxostore: %s: %w", filepath.Join(dir, IndexFile), err)
58 }
59 out := make(map[uint32]chainhash.Hash)
60 for _, line := range strings.Split(string(raw), "\n") {
61 if line == "" {
62 continue
63 }
64 heightText, hashText, ok := strings.Cut(line, " ")
65 if !ok {
66 return nil, fmt.Errorf("utxostore: %s: %q is not a height and a name", IndexFile, line)
67 }
68 h, err := strconv.ParseUint(heightText, 10, 32)
69 if err != nil {
70 return nil, fmt.Errorf("utxostore: %s: %q", IndexFile, line)
71 }
72 name, err := chainhash.NewHashFromStr(hashText)
73 if err != nil {
74 return nil, fmt.Errorf("utxostore: %s: %q", IndexFile, line)
75 }
76 out[uint32(h)] = *name
77 }
78 return out, nil
79 }
80 81 // DiffFile is the name a checkpoint diff is written under: from the checkpoint
82 // at From to the checkpoint at To.
83 func DiffFile(from, to uint32) string { return fmt.Sprintf("diff-%09d-%09d.dat", from, to) }
84 85 // WriteSet writes a sorted set to dir under a name that is not a checkpoint's,
86 // and returns the set's name: double SHA-256 of the encoded entries in order.
87 //
88 // A checkpoint's own file is written by the merge, because only the merge knows
89 // the offsets a diff's records point at. This function is the replay's record
90 // of what the set should be, and the merge's name is checked against it.
91 //
92 // The name is computed over the entries as they are written, so a caller that
93 // streams a set from a replay does not have to hold it to name it.
94 func WriteSet(dir string, height uint32, set []utxo.Entry) (chainhash.Hash, error) {
95 buf := make([]byte, EntrySize)
96 h := newHasher()
97 f, err := os.Create(filepath.Join(dir, ReplayFile(height)))
98 if err != nil {
99 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
100 }
101 w := bufio.NewWriterSize(f, 1<<20)
102 for i := range set {
103 set[i].Encode(buf)
104 h.Write(buf)
105 if _, err := w.Write(buf); err != nil {
106 f.Close()
107 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
108 }
109 }
110 if err := w.Flush(); err != nil {
111 f.Close()
112 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
113 }
114 if err := f.Sync(); err != nil {
115 f.Close()
116 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
117 }
118 if err := f.Close(); err != nil {
119 return chainhash.Hash{}, err
120 }
121 return h.Sum(), nil
122 }
123 124 // WriteSetFile writes a sorted set to dir under the checkpoint name for a
125 // height, creating the directory, and returns the set's name.
126 //
127 // The name is computed over the entries as they are written, so the builder does
128 // not hold the encoding to name it. This is the snapshot the service serves: one
129 // file per retarget height, no replay copy beside it.
130 func WriteSetFile(dir string, height uint32, set []utxo.Entry) (chainhash.Hash, error) {
131 if err := os.MkdirAll(dir, 0o755); err != nil {
132 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
133 }
134 buf := make([]byte, EntrySize)
135 h := newHasher()
136 f, err := os.Create(filepath.Join(dir, SetFile(height)))
137 if err != nil {
138 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
139 }
140 w := bufio.NewWriterSize(f, 1<<20)
141 for i := range set {
142 set[i].Encode(buf)
143 h.Write(buf)
144 if _, err := w.Write(buf); err != nil {
145 f.Close()
146 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
147 }
148 }
149 if err := w.Flush(); err != nil {
150 f.Close()
151 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
152 }
153 if err := f.Sync(); err != nil {
154 f.Close()
155 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
156 }
157 if err := f.Close(); err != nil {
158 return chainhash.Hash{}, err
159 }
160 name := h.Sum()
161 if err := RecordName(dir, height, name); err != nil {
162 return chainhash.Hash{}, err
163 }
164 return name, nil
165 }
166 167 // ReplayFile is the name a replay writes its set under.
168 func ReplayFile(height uint32) string { return fmt.Sprintf("replay-%09d.dat", height) }
169 170 // LoadReplay reads a replay's set back, in order.
171 func LoadReplay(dir string, height uint32) ([]utxo.Entry, error) {
172 f, err := os.Open(filepath.Join(dir, ReplayFile(height)))
173 if err != nil {
174 return nil, fmt.Errorf("utxostore: %w", err)
175 }
176 defer f.Close()
177 var out []utxo.Entry
178 buf := make([]byte, EntrySize)
179 r := bufio.NewReaderSize(f, 1<<20)
180 for {
181 if _, err := io.ReadFull(r, buf); err != nil {
182 if errors.Is(err, io.EOF) {
183 break
184 }
185 return nil, fmt.Errorf("utxostore: set %d: %w", height, err)
186 }
187 out = append(out, utxo.Decode(buf))
188 }
189 return out, nil
190 }
191 192 // Promote copies the a replay's set into a checkpoint's file. It is how the
193 // base set is laid down; every later checkpoint is the merge's to write,
194 // because only the merge knows the offsets.
195 func Promote(dir string, height uint32) (chainhash.Hash, error) {
196 raw, err := os.ReadFile(filepath.Join(dir, ReplayFile(height)))
197 if err != nil {
198 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
199 }
200 if err := os.WriteFile(filepath.Join(dir, SetFile(height)), raw, 0o644); err != nil {
201 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
202 }
203 return chainhash.DoubleHashH(raw), nil
204 }
205 206 // NameReplay is the name a replay's set file hashes to, without holding it.
207 func NameReplay(dir string, height uint32) (chainhash.Hash, error) {
208 f, err := os.Open(filepath.Join(dir, ReplayFile(height)))
209 if err != nil {
210 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
211 }
212 defer f.Close()
213 return hashReader(f)
214 }
215 216 // CutRange turns the touches of [from,to) into a diff and writes it.
217 //
218 // The touches come from the chain's blocks applied to the set at from, which
219 // is the caller's replay. The diff is the touches sorted by outpoint, the form
220 // a merge consumes, so the cut does not depend on the order the blocks were
221 // walked in.
222 func CutRange(dir string, from, to uint32, touches []utxo.Touch) (chainhash.Hash, error) {
223 if err := os.MkdirAll(dir, 0o755); err != nil {
224 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
225 }
226 d := utxo.Diff{From: from, To: to, Touches: touches}
227 raw := d.Encode()
228 if err := os.WriteFile(filepath.Join(dir, DiffFile(from, to)), raw, 0o644); err != nil {
229 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
230 }
231 return chainhash.DoubleHashH(raw), nil
232 }
233 234 // LoadDiff reads a diff written by CutRange.
235 func LoadDiff(dir string, from, to uint32) (utxo.Diff, error) {
236 raw, err := os.ReadFile(filepath.Join(dir, DiffFile(from, to)))
237 if err != nil {
238 return utxo.Diff{}, fmt.Errorf("utxostore: %w", err)
239 }
240 d, err := utxo.DecodeDiff(raw)
241 if err != nil {
242 return utxo.Diff{}, fmt.Errorf("utxostore: %w", err)
243 }
244 if d.From != from || d.To != to {
245 return utxo.Diff{}, fmt.Errorf("utxostore: %s holds %d-%d, not %d-%d", DiffFile(from, to), d.From, d.To, from, to)
246 }
247 return d, nil
248 }
249 250 // LoadSet reads a snapshot's entries in order.
251 func LoadSet(dir string, height uint32) ([]utxo.Entry, error) {
252 raw, err := os.ReadFile(filepath.Join(dir, SetFile(height)))
253 if err != nil {
254 return nil, fmt.Errorf("utxostore: %w", err)
255 }
256 if len(raw)%EntrySize != 0 {
257 return nil, fmt.Errorf("utxostore: %s is %d bytes, not a whole number of entries", SetFile(height), len(raw))
258 }
259 out := make([]utxo.Entry, 0, len(raw)/EntrySize)
260 buf := make([]byte, EntrySize)
261 for i := 0; i+EntrySize <= len(raw); i += EntrySize {
262 copy(buf, raw[i:i+EntrySize])
263 out = append(out, utxo.Decode(buf))
264 }
265 return out, nil
266 }
267 268 // NameOf is the name of a set a caller already holds, computed the same way
269 // WriteSet computes it.
270 func NameOf(set []utxo.Entry) chainhash.Hash {
271 buf := make([]byte, EntrySize)
272 h := newHasher()
273 for i := range set {
274 set[i].Encode(buf)
275 _, _ = h.Write(buf)
276 }
277 return h.Sum()
278 }
279 280 // SetName is the name a set file hashes to, without loading it. It is what a
281 // client checks a checkpoint against after applying the diffs that reach it.
282 func SetName(dir string, height uint32) (chainhash.Hash, error) {
283 f, err := os.Open(filepath.Join(dir, SetFile(height)))
284 if err != nil {
285 return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err)
286 }
287 defer f.Close()
288 return hashReader(f)
289 }
290 291 func newHasher() *hasher { return &hasher{h: sha256.New()} }
292 293 // hasher is a SHA-256 writer that keeps the running double hash.
294 type hasher struct {
295 h hashState
296 }
297 298 func (h *hasher) Write(b []byte) (int, error) { return h.h.Write(b) }
299 300 func (h *hasher) Sum() chainhash.Hash {
301 first := h.h.Sum(nil)
302 second := sha256.Sum256(first)
303 var out chainhash.Hash
304 copy(out[:], second[:])
305 return out
306 }
307 308 // hashReader names a stream: double SHA-256 of every byte in it.
309 func hashReader(r io.Reader) (chainhash.Hash, error) {
310 first := newSHA()
311 buf := make([]byte, 1<<20)
312 for {
313 n, err := r.Read(buf)
314 if n > 0 {
315 _, _ = first.Write(buf[:n])
316 }
317 if errors.Is(err, io.EOF) {
318 break
319 }
320 if err != nil {
321 return chainhash.Hash{}, err
322 }
323 }
324 second := newSHA()
325 _, _ = second.Write(first.Sum(nil))
326 var out chainhash.Hash
327 copy(out[:], second.Sum(nil))
328 return out, nil
329 }
330 331 // SortedTouches is a convenience for a caller that has touched outpoints in
332 // block order and needs them in the diff's order. ApplyRange sorts its own
333 // input and refuses duplicate touches, so this exists for a caller that wants
334 // the order without applying anything.
335 func SortedTouches(ts []utxo.Touch) {
336 sort.SliceStable(ts, func(i, j int) bool {
337 return bytes.Compare(ts[i].OutPoint.Hash[:], ts[j].OutPoint.Hash[:]) < 0 ||
338 (ts[i].OutPoint.Hash == ts[j].OutPoint.Hash && ts[i].OutPoint.Index < ts[j].OutPoint.Index)
339 })
340 }
341 342 // RecordName adds a snapshot to a directory's index.
343 //
344 // The index is how a reader learns every snapshot's name without reading every
345 // snapshot, so each writer of a snapshot has to record it: a set no manifest
346 // knows about is a set no client fetches.
347 func RecordName(dir string, height uint32, name chainhash.Hash) error {
348 idx, err := os.OpenFile(filepath.Join(dir, IndexFile), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
349 if err != nil {
350 return fmt.Errorf("utxostore: %w", err)
351 }
352 if _, err := idx.Write(indexLine(height, name)); err != nil {
353 idx.Close()
354 return fmt.Errorf("utxostore: %w", err)
355 }
356 if err := idx.Close(); err != nil {
357 return fmt.Errorf("utxostore: %w", err)
358 }
359 return nil
360 }
361