// Package utxostore holds a canonical UTXO set at a height, in files, and the // checkpoints cut from it. // // The on-disk form is the plan's: a set is a sequence of sorted chunks of // fixed-width entries, each readable and mergeable on its own, so applying a // range's diff to it is a sequential merge rather than a load into memory. // A checkpoint is a diff against the last checkpoint at or below its height, // and the chain of those diffs from the genesis base is what a client applies // to reach any checkpoint height. // // Nothing here is verified by trust: a checkpoint carries the name of the set // it describes, and a client that applies the diffs recomputes that name from // the result. A wrong diff gives a different name, and the client says so. package utxostore import ( "bufio" "bytes" "crypto/sha256" "errors" "fmt" "io" "os" "path/filepath" "sort" "strconv" "strings" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/utxo" ) // EntrySize is the encoded width of an entry. const EntrySize = utxo.EntryEncodeSize // SetFile is the name a canonical set is written under at a height. func SetFile(height uint32) string { return fmt.Sprintf("set-%09d.dat", height) } // IndexFile records every snapshot's height and name in a directory. // // A manifest needs the name of every snapshot, and the name is the double // SHA-256 of the file, so naming them by reading them back means reading the // whole dataset to answer one request. The writer knows each name as it writes // it, so it records it here and a reader reads one small file. const IndexFile = "index" // indexLine is one record: the height in decimal, a space, the name in hex. func indexLine(height uint32, name chainhash.Hash) []byte { return []byte(fmt.Sprintf("%d %s\n", height, name)) } // Names reads a directory's snapshot index: height to set name. func Names(dir string) (map[uint32]chainhash.Hash, error) { raw, err := os.ReadFile(filepath.Join(dir, IndexFile)) if err != nil { return nil, fmt.Errorf("utxostore: %s: %w", filepath.Join(dir, IndexFile), err) } out := make(map[uint32]chainhash.Hash) for _, line := range strings.Split(string(raw), "\n") { if line == "" { continue } heightText, hashText, ok := strings.Cut(line, " ") if !ok { return nil, fmt.Errorf("utxostore: %s: %q is not a height and a name", IndexFile, line) } h, err := strconv.ParseUint(heightText, 10, 32) if err != nil { return nil, fmt.Errorf("utxostore: %s: %q", IndexFile, line) } name, err := chainhash.NewHashFromStr(hashText) if err != nil { return nil, fmt.Errorf("utxostore: %s: %q", IndexFile, line) } out[uint32(h)] = *name } return out, nil } // DiffFile is the name a checkpoint diff is written under: from the checkpoint // at From to the checkpoint at To. func DiffFile(from, to uint32) string { return fmt.Sprintf("diff-%09d-%09d.dat", from, to) } // WriteSet writes a sorted set to dir under a name that is not a checkpoint's, // and returns the set's name: double SHA-256 of the encoded entries in order. // // A checkpoint's own file is written by the merge, because only the merge knows // the offsets a diff's records point at. This function is the replay's record // of what the set should be, and the merge's name is checked against it. // // The name is computed over the entries as they are written, so a caller that // streams a set from a replay does not have to hold it to name it. func WriteSet(dir string, height uint32, set []utxo.Entry) (chainhash.Hash, error) { buf := make([]byte, EntrySize) h := newHasher() f, err := os.Create(filepath.Join(dir, ReplayFile(height))) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } w := bufio.NewWriterSize(f, 1<<20) for i := range set { set[i].Encode(buf) h.Write(buf) if _, err := w.Write(buf); err != nil { f.Close() return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } } if err := w.Flush(); err != nil { f.Close() return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } if err := f.Sync(); err != nil { f.Close() return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } if err := f.Close(); err != nil { return chainhash.Hash{}, err } return h.Sum(), nil } // WriteSetFile writes a sorted set to dir under the checkpoint name for a // height, creating the directory, and returns the set's name. // // The name is computed over the entries as they are written, so the builder does // not hold the encoding to name it. This is the snapshot the service serves: one // file per retarget height, no replay copy beside it. func WriteSetFile(dir string, height uint32, set []utxo.Entry) (chainhash.Hash, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } buf := make([]byte, EntrySize) h := newHasher() f, err := os.Create(filepath.Join(dir, SetFile(height))) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } w := bufio.NewWriterSize(f, 1<<20) for i := range set { set[i].Encode(buf) h.Write(buf) if _, err := w.Write(buf); err != nil { f.Close() return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } } if err := w.Flush(); err != nil { f.Close() return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } if err := f.Sync(); err != nil { f.Close() return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } if err := f.Close(); err != nil { return chainhash.Hash{}, err } name := h.Sum() if err := RecordName(dir, height, name); err != nil { return chainhash.Hash{}, err } return name, nil } // ReplayFile is the name a replay writes its set under. func ReplayFile(height uint32) string { return fmt.Sprintf("replay-%09d.dat", height) } // LoadReplay reads a replay's set back, in order. func LoadReplay(dir string, height uint32) ([]utxo.Entry, error) { f, err := os.Open(filepath.Join(dir, ReplayFile(height))) if err != nil { return nil, fmt.Errorf("utxostore: %w", err) } defer f.Close() var out []utxo.Entry buf := make([]byte, EntrySize) r := bufio.NewReaderSize(f, 1<<20) for { if _, err := io.ReadFull(r, buf); err != nil { if errors.Is(err, io.EOF) { break } return nil, fmt.Errorf("utxostore: set %d: %w", height, err) } out = append(out, utxo.Decode(buf)) } return out, nil } // Promote copies the a replay's set into a checkpoint's file. It is how the // base set is laid down; every later checkpoint is the merge's to write, // because only the merge knows the offsets. func Promote(dir string, height uint32) (chainhash.Hash, error) { raw, err := os.ReadFile(filepath.Join(dir, ReplayFile(height))) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } if err := os.WriteFile(filepath.Join(dir, SetFile(height)), raw, 0o644); err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } return chainhash.DoubleHashH(raw), nil } // NameReplay is the name a replay's set file hashes to, without holding it. func NameReplay(dir string, height uint32) (chainhash.Hash, error) { f, err := os.Open(filepath.Join(dir, ReplayFile(height))) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } defer f.Close() return hashReader(f) } // CutRange turns the touches of [from,to) into a diff and writes it. // // The touches come from the chain's blocks applied to the set at from, which // is the caller's replay. The diff is the touches sorted by outpoint, the form // a merge consumes, so the cut does not depend on the order the blocks were // walked in. func CutRange(dir string, from, to uint32, touches []utxo.Touch) (chainhash.Hash, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } d := utxo.Diff{From: from, To: to, Touches: touches} raw := d.Encode() if err := os.WriteFile(filepath.Join(dir, DiffFile(from, to)), raw, 0o644); err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } return chainhash.DoubleHashH(raw), nil } // LoadDiff reads a diff written by CutRange. func LoadDiff(dir string, from, to uint32) (utxo.Diff, error) { raw, err := os.ReadFile(filepath.Join(dir, DiffFile(from, to))) if err != nil { return utxo.Diff{}, fmt.Errorf("utxostore: %w", err) } d, err := utxo.DecodeDiff(raw) if err != nil { return utxo.Diff{}, fmt.Errorf("utxostore: %w", err) } if d.From != from || d.To != to { return utxo.Diff{}, fmt.Errorf("utxostore: %s holds %d-%d, not %d-%d", DiffFile(from, to), d.From, d.To, from, to) } return d, nil } // LoadSet reads a snapshot's entries in order. func LoadSet(dir string, height uint32) ([]utxo.Entry, error) { raw, err := os.ReadFile(filepath.Join(dir, SetFile(height))) if err != nil { return nil, fmt.Errorf("utxostore: %w", err) } if len(raw)%EntrySize != 0 { return nil, fmt.Errorf("utxostore: %s is %d bytes, not a whole number of entries", SetFile(height), len(raw)) } out := make([]utxo.Entry, 0, len(raw)/EntrySize) buf := make([]byte, EntrySize) for i := 0; i+EntrySize <= len(raw); i += EntrySize { copy(buf, raw[i:i+EntrySize]) out = append(out, utxo.Decode(buf)) } return out, nil } // NameOf is the name of a set a caller already holds, computed the same way // WriteSet computes it. func NameOf(set []utxo.Entry) chainhash.Hash { buf := make([]byte, EntrySize) h := newHasher() for i := range set { set[i].Encode(buf) _, _ = h.Write(buf) } return h.Sum() } // SetName is the name a set file hashes to, without loading it. It is what a // client checks a checkpoint against after applying the diffs that reach it. func SetName(dir string, height uint32) (chainhash.Hash, error) { f, err := os.Open(filepath.Join(dir, SetFile(height))) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } defer f.Close() return hashReader(f) } func newHasher() *hasher { return &hasher{h: sha256.New()} } // hasher is a SHA-256 writer that keeps the running double hash. type hasher struct { h hashState } func (h *hasher) Write(b []byte) (int, error) { return h.h.Write(b) } func (h *hasher) Sum() chainhash.Hash { first := h.h.Sum(nil) second := sha256.Sum256(first) var out chainhash.Hash copy(out[:], second[:]) return out } // hashReader names a stream: double SHA-256 of every byte in it. func hashReader(r io.Reader) (chainhash.Hash, error) { first := newSHA() buf := make([]byte, 1<<20) for { n, err := r.Read(buf) if n > 0 { _, _ = first.Write(buf[:n]) } if errors.Is(err, io.EOF) { break } if err != nil { return chainhash.Hash{}, err } } second := newSHA() _, _ = second.Write(first.Sum(nil)) var out chainhash.Hash copy(out[:], second.Sum(nil)) return out, nil } // SortedTouches is a convenience for a caller that has touched outpoints in // block order and needs them in the diff's order. ApplyRange sorts its own // input and refuses duplicate touches, so this exists for a caller that wants // the order without applying anything. func SortedTouches(ts []utxo.Touch) { sort.SliceStable(ts, func(i, j int) bool { return bytes.Compare(ts[i].OutPoint.Hash[:], ts[j].OutPoint.Hash[:]) < 0 || (ts[i].OutPoint.Hash == ts[j].OutPoint.Hash && ts[i].OutPoint.Index < ts[j].OutPoint.Index) }) } // RecordName adds a snapshot to a directory's index. // // The index is how a reader learns every snapshot's name without reading every // snapshot, so each writer of a snapshot has to record it: a set no manifest // knows about is a set no client fetches. func RecordName(dir string, height uint32, name chainhash.Hash) error { idx, err := os.OpenFile(filepath.Join(dir, IndexFile), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { return fmt.Errorf("utxostore: %w", err) } if _, err := idx.Write(indexLine(height, name)); err != nil { idx.Close() return fmt.Errorf("utxostore: %w", err) } if err := idx.Close(); err != nil { return fmt.Errorf("utxostore: %w", err) } return nil }