package utxostore import ( "bufio" "encoding/binary" "errors" "fmt" "io" "os" "path/filepath" "sort" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/utxo" "git.smesh.lol/btcd-lite/internal/wire" ) const entrySize = utxo.EntryEncodeSize // cmpOp is the set's own comparison. It used to or the hash comparison with // the index comparison, and a bitwise or of two -1s is -1, so two outpoints // that differed in both a hash and an index could order one way here and the // other way in the set. The merge walks the base with this and the creations // with the set's comparison, so a disagreement between them puts a creation in // the wrong place; it takes outpoints that differ in many hash bytes to show // up, which is why a synthetic chain never did and a node's did. func cmpOp(a, b wire.OutPoint) int { return utxo.CompareOutPoints(a, b) } // keyList is a sorted, deduplicated list of outpoints as 36-byte keys, with // the file a parallel lookup reads each key's entry from. // // i is the index of cur, the key not yet consumed; advance moves to the next. type keyList struct { f *os.File v *os.File n int i int cur wire.OutPoint have bool } func openKeys(path string) (*keyList, error) { f, err := os.Open(path) if err != nil { return nil, err } fi, err := f.Stat() if err != nil { f.Close() return nil, err } // i is -1 until advance reads the first key, which is where advance's own // increment expects to start. k := &keyList{f: f, n: int(fi.Size() / 36), i: -1} k.advance() return k, nil } // advance moves cur to the next key. The caller consumes the key it already // held; this leaves the next one in cur. func (k *keyList) advance() { k.i++ if k.i >= k.n { k.have = false return } var b [36]byte if _, err := k.f.ReadAt(b[:], int64(k.i)*36); err != nil { k.have = false return } copy(k.cur.Hash[:], b[:32]) k.cur.Index = binary.LittleEndian.Uint32(b[32:36]) k.have = true } // openValues attaches the entry file that runs parallel to the key file. func (k *keyList) openValues(path string) error { f, err := os.Open(path) if err != nil { return err } k.v = f return nil } func (k *keyList) close() { k.f.Close() if k.v != nil { k.v.Close() } } // entry reads the value file's record for key i, which is the record of the // key's creation in the diff. func (k *keyList) entry(i int) (utxo.Entry, bool) { if k.v == nil { return utxo.Entry{}, false } buf := make([]byte, entrySize) // The entry's offset is the key's record index, shifted to the value file's // record size: the two files are parallel by construction, and a bug that // read them at different indices would write one key's value under // another's, which is the one thing a merge must never do. if _, err := k.v.ReadAt(buf, int64(i)*int64(entrySize)); err != nil { return utxo.Entry{}, false } e := utxo.Decode(buf) return e, true } // MergeRange writes the set at to from the set at from and the diff of the // range between them, in one pass each over the base and the diff. // // The diff is the end state of the range: its created touches are the // outpoints the range made and did not spend again, and its spent touches are // the ones it took from the base. The merge walks the base and both key lists // in outpoint order and writes the union minus the spends plus the creations. // // target, when set, is the name the set was given when the caller wrote it by // replay; a merge that does not reproduce it says so instead of writing a // second answer to the same question. func MergeRange(dir string, from, to uint32, diff utxo.Diff, target chainhash.Hash) (chainhash.Hash, error) { return MergeRangeFrom(dir, dir, from, to, diff, target) } // MergeRangeFrom is MergeRange with the snapshot it starts from read somewhere // else. A chain that continues a shared prefix reads the prefix's snapshot where // the prefix wrote it and writes its own next to itself, so the largest file in // the dataset is not copied once per chain. func MergeRangeFrom(baseDir, dir string, from, to uint32, diff utxo.Diff, target chainhash.Hash) (chainhash.Hash, error) { createdPath := filepath.Join(dir, fmt.Sprintf("keys-%09d-%09d.created", from, to)) spentPath := filepath.Join(dir, fmt.Sprintf("keys-%09d-%09d.spent", from, to)) if err := checkChain(diff, from); err != nil { return chainhash.Hash{}, err } if err := writeKeys(createdPath, spentPath, diff); err != nil { return chainhash.Hash{}, err } if !keepScratch { defer os.Remove(createdPath) defer os.Remove(spentPath) } created, err := openKeys(createdPath) if err != nil { return chainhash.Hash{}, err } defer created.close() if !keepScratch { defer os.Remove(createdPath + "v") } if created.v, err = os.Open(createdPath + "v"); err != nil { return chainhash.Hash{}, err } spent, err := openKeys(spentPath) if err != nil { return chainhash.Hash{}, err } defer spent.close() base, err := os.Open(filepath.Join(baseDir, SetFile(from))) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } defer base.Close() out, err := os.Create(filepath.Join(dir, SetFile(to))) if err != nil { return chainhash.Hash{}, fmt.Errorf("utxostore: %w", err) } w := bufio.NewWriterSize(out, 1<<20) h := newHasher() // buf holds the base entry being walked, and cbuf holds a creation's entry. // They are separate because writeCreated writes through its buffer: passing // buf to it would overwrite the base entry before writeEntry emitted it, and // the creation would come out twice while the base entry came out never. buf := make([]byte, entrySize) cbuf := make([]byte, entrySize) baseR := bufio.NewReaderSize(base, 1<<20) for { _, rerr := io.ReadFull(baseR, buf) if errors.Is(rerr, io.EOF) { break } if rerr != nil { out.Close() return chainhash.Hash{}, fmt.Errorf("utxostore: base %d: %w", from, rerr) } e := utxo.Decode(buf) debugStep(e.OutPoint, created.i, created.cur, created.have, spent.cur, spent.have) action := "keep" if spent.have && spent.cur == e.OutPoint { action = "spend" } else if created.have && created.cur == e.OutPoint { action = "create-at-base" } debugWalk(e.OutPoint, created.cur, spent.cur, action) // The created list first: a creation below this entry is new and // sorts before it, so it is written now. for created.have && cmpOp(created.cur, e.OutPoint) < 0 { writeCreated(w, h, cbuf, created) } // A creation that sorts before this entry is written first, whether or // not the entry is about to be spent: whether the base entry survives // does not change where the creations around it belong. if spent.have && spent.cur == e.OutPoint { spent.advance() // The creations below this entry still come before it. The prefix // loop at the top of this iteration wrote the ones below the entry // it started on, which is this entry, so they were already written; // nothing is written here, and writing them again is how one // creation came out twice. continue } if spent.have && cmpOp(spent.cur, e.OutPoint) < 0 { out.Close() return chainhash.Hash{}, fmt.Errorf("utxostore: the range spends %s, which the set at %d does not hold", spent.cur, from) } if created.have && created.cur == e.OutPoint { // The diff's creation names an outpoint the base holds: the // creation is of an output the set already has, and the entry the // set holds is the one written. The created list moves on either // way, so the same outpoint is not written twice. created.advance() } writeEntry(w, h, buf) } for created.have { writeCreated(w, h, cbuf, created) } if err := w.Flush(); err != nil { out.Close() return chainhash.Hash{}, err } if err := out.Sync(); err != nil { out.Close() return chainhash.Hash{}, err } if err := out.Close(); err != nil { return chainhash.Hash{}, err } name := h.Sum() if target != (chainhash.Hash{}) && name != target { os.Remove(filepath.Join(dir, SetFile(to))) return chainhash.Hash{}, fmt.Errorf("utxostore: merging to %d gives %s, the replay wrote %s", to, name, target) } // A merged snapshot is a snapshot: it goes in the index like one the replay // wrote, or a manifest never offers it and a client never fetches it. if err := RecordName(dir, to, name); err != nil { return chainhash.Hash{}, err } return name, nil } // writeCreated emits the next created outpoint, which is k.cur, moves the key // list on, and reads the entry the diff recorded for it. func writeCreated(w *bufio.Writer, h hashWriter, buf []byte, k *keyList) { idx := k.i op := k.cur debugWrite(op, k.n) // The lookup in the value file is advisory: its outpoint never reaches the // set. The creation the diff recorded IS this outpoint at THIS height, and // the key file's index is the only thing that says which entry belongs to // which key. A value file read at a stale index once put a creation at // another block's height, and taking the outpoint from it put a creation // in another outpoint's place; both are why the entry is built here. e, ok := k.entry(idx) if !ok { debugPairMiss(op, e, idx, ok) e = utxo.Entry{OutPoint: op} } e.OutPoint = op debugCreated(idx, e) e.Encode(buf) writeEntry(w, h, buf) k.advance() } // debugPairMiss is a switch the package's tests flip to see a pairing failure // as it happens. var debugPairMiss = func(op wire.OutPoint, e utxo.Entry, idx int, ok bool) {} // debugCreated is a switch the package's tests flip to see each creation the // merge writes, with the index it read the entry from. var debugCreated = func(idx int, e utxo.Entry) {} // keepScratch leaves the merge's key files behind for a test that reads them. var keepScratch = false // debugWrite is a switch the package's tests flip to see each creation written, // with the key count the list had, so a write from the wrong list is visible. var debugWrite = func(op wire.OutPoint, n int) {} // debugWalk is a switch the package's tests flip to see each base entry the // merge walks, with the cursor positions and what it chose to do. // debugWrittenOut sees the outpoint a creation was meant to be and the outpoint // the bytes about to be hashed name, which differ only if the buffer lied. var debugWrittenOut = func(meant, got wire.OutPoint) {} var debugWalk = func(base wire.OutPoint, createdOp wire.OutPoint, spentOp wire.OutPoint, wrote string) {} // debugStep is a switch the package's tests flip to see each iteration of the // merge's walk: which base entry it is on, and where both cursors stand. var debugStep = func(base wire.OutPoint, createdIdx int, created wire.OutPoint, createdHave bool, spent wire.OutPoint, spentHave bool) { } func writeEntry(w *bufio.Writer, h hashWriter, buf []byte) { _, _ = w.Write(buf) // The name is the name of the set, not of the writes: the bytes are // normalised through the entry type before they are hashed, so a buffer // that kept a field from an earlier entry cannot change the name. e := utxo.Decode(buf) e.Encode(buf) _, _ = h.Write(buf) } type hashWriter = interface { Write([]byte) (int, error) } // writeKeys writes the diff's net created and net spent outpoints, sorted, and // a parallel file of the created entries, one record per key and in the same // order. func writeKeys(createdPath, spentPath string, diff utxo.Diff) error { net := make(map[wire.OutPoint]byte, len(diff.Touches)) for _, t := range diff.Touches { if t.Spent { if net[t.OutPoint] == 1 { // Created earlier in the range and spent later: gone by the // end of it, and neither side of the merge. delete(net, t.OutPoint) continue } net[t.OutPoint] = 2 continue } net[t.OutPoint] = 1 } values := make(map[wire.OutPoint]utxo.Entry, len(net)) for _, t := range diff.Touches { if !t.Spent && net[t.OutPoint] == 1 { values[t.OutPoint] = t.New } } var created, spent []wire.OutPoint for op, kind := range net { switch kind { case 1: created = append(created, op) case 2: spent = append(spent, op) } } // One order for the key list and the walk: the set's own comparison. The // merge's walk and writeKeys' sort must sort keys identically, and two // comparisons that disagree on one pair of outpoints is exactly how a merge // writes a set in an order nothing else produces. sortBySet(created) sortBySet(spent) if err := writeOpList(createdPath, created); err != nil { return err } entries := make([]utxo.Entry, len(created)) for i, op := range created { entries[i] = values[op] } if err := writeEntryPairs(createdPath+"v", entries, created); err != nil { return err } return writeOpList(spentPath, spent) } // sortBySet sorts outpoints by the set's comparison, so the key files and the // set it produces cannot disagree about order. func sortBySet(ops []wire.OutPoint) { sort.Slice(ops, func(i, j int) bool { return utxo.LessEntry(utxo.Entry{OutPoint: ops[i]}, utxo.Entry{OutPoint: ops[j]}) }) } // writeEntryPairs writes the created entries, one per key, refusing a pair // whose entry names another outpoint: the key file is index i and the entry // file is index i, and nothing else is a merge. func writeEntryPairs(path string, created []utxo.Entry, keys []wire.OutPoint) error { f, err := os.Create(path) if err != nil { return fmt.Errorf("utxostore: %w", err) } defer f.Close() w := bufio.NewWriterSize(f, 1<<20) buf := make([]byte, entrySize) for i := range created { if created[i].OutPoint != keys[i] { return fmt.Errorf("utxostore: entry %d is for %s, key %d is %s", i, created[i].OutPoint, i, keys[i]) } created[i].Encode(buf) if _, err := w.Write(buf); err != nil { return err } } return w.Flush() } func writeOpList(path string, ops []wire.OutPoint) error { f, err := os.Create(path) if err != nil { return fmt.Errorf("utxostore: %w", err) } defer f.Close() w := bufio.NewWriterSize(f, 1<<20) var key [36]byte for _, op := range ops { copy(key[:32], op.Hash[:]) binary.LittleEndian.PutUint32(key[32:], op.Index) if _, err := w.Write(key[:]); err != nil { return err } } return w.Flush() } // checkChain refuses a diff whose own touches do not describe a range: a spend // before the creation of the same outpoint, two spends of one outpoint in the // range, or two creations, are chains that cannot exist. It is the same rule // utxo.ApplyRange applies to a range, stated over the sorted touches so the // merge does not have to hold the base to check it. func checkChain(diff utxo.Diff, from uint32) error { if diff.From != from || diff.To < from { return fmt.Errorf("utxostore: diff is %d..%d, the merge is %d", diff.From, diff.To, from) } ts := append([]utxo.Touch(nil), diff.Touches...) sort.SliceStable(ts, func(i, j int) bool { if c := cmpOp(ts[i].OutPoint, ts[j].OutPoint); c != 0 { return c < 0 } if ts[i].Height != ts[j].Height { return ts[i].Height < ts[j].Height } return !ts[i].Spent && ts[j].Spent }) for i := 1; i < len(ts); i++ { if ts[i].OutPoint != ts[i-1].OutPoint || ts[i].Spent != ts[i-1].Spent { continue } if ts[i].Spent { return fmt.Errorf("utxostore: outpoint %s spent twice in one range", ts[i].OutPoint) } return fmt.Errorf("utxostore: outpoint %s created twice in one range", ts[i].OutPoint) } return nil }